本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$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()