翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$addToSet
$addToSet 集計演算子は、各グループの指定された式から一意の値の配列を返します。$group ステージ内で使用して個別の値を蓄積し、重複を自動的に排除します。
パラメータ
例 (MongoDB シェル)
次の例は、 $addToSet演算子を使用して、顧客ごとに注文が行われた一意の都市を収集する方法を示しています。
サンプルドキュメントを作成する
db.orders.insertMany([
{ _id: 1, customer: "Alice", city: "Seattle", amount: 100 },
{ _id: 2, customer: "Alice", city: "Portland", amount: 150 },
{ _id: 3, customer: "Bob", city: "Seattle", amount: 200 },
{ _id: 4, customer: "Alice", city: "Seattle", amount: 75 },
{ _id: 5, customer: "Bob", city: "Boston", amount: 300 }
]);
クエリの例
db.orders.aggregate([
{
$group: {
_id: "$customer",
cities: { $addToSet: "$city" }
}
}
]);
出力
[
{ _id: 'Bob', cities: [ 'Seattle', 'Boston' ] },
{ _id: 'Alice', cities: [ 'Seattle', 'Portland' ] }
]
コードの例
$addToSet 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('orders');
const result = await collection.aggregate([
{
$group: {
_id: "$customer",
cities: { $addToSet: "$city" }
}
}
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['orders']
result = list(collection.aggregate([
{
'$group': {
'_id': '$customer',
'cities': { '$addToSet': '$city' }
}
}
]))
print(result)
client.close()
example()