View a markdown version of this page

$addToSet - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$addToSet

$addToSet 彙總運算子會從每個群組的指定表達式傳回唯一值的陣列。它會在$group階段內用來累積不同的值,自動消除重複項目。

參數

  • expression:要評估群組中每個文件的表達式。

範例 (MongoDB Shell)

下列範例示範如何使用 $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' ] } ]

視窗運算子用量範例 (MongoDB Shell)

8.0.2 版的新功能。

該$addToSet運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會傳回每個視窗中文件指定表達式的唯一值陣列。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。

注意

在 中用作視窗運算子時$setWindowFields, 限制$addToSet為 100 MB 的中繼資料。超過此限制的操作會傳回錯誤。

建立範例文件

db.visits.insertMany([ { _id: 1, customer: "Alice", day: 1, city: "Seattle" }, { _id: 2, customer: "Alice", day: 2, city: "Portland" }, { _id: 3, customer: "Alice", day: 3, city: "Seattle" }, { _id: 4, customer: "Bob", day: 1, city: "Boston" }, { _id: 5, customer: "Bob", day: 2, city: "Boston" } ]);

查詢範例

下列範例會依 分割文件customer、依 排序每個分割區day,並傳回分割區開頭到目前文件的一組唯一city值。

db.visits.aggregate([ { $setWindowFields: { partitionBy: "$customer", sortBy: { day: 1 }, output: { citiesSoFar: { $addToSet: "$city", window: { documents: ["unbounded", "current"] } } } } } ]);

輸出

[ { "_id": 1, "customer": "Alice", "day": 1, "city": "Seattle", "citiesSoFar": [ "Seattle" ] }, { "_id": 2, "customer": "Alice", "day": 2, "city": "Portland", "citiesSoFar": [ "Portland", "Seattle" ] }, { "_id": 3, "customer": "Alice", "day": 3, "city": "Seattle", "citiesSoFar": [ "Portland", "Seattle" ] }, { "_id": 4, "customer": "Bob", "day": 1, "city": "Boston", "citiesSoFar": [ "Boston" ] }, { "_id": 5, "customer": "Bob", "day": 2, "city": "Boston", "citiesSoFar": [ "Boston" ] } ]

每個文件都會以 擴增citiesSoFar,這是其分割區內從開始到目前文件的一組唯一city值。如同累積器表單,不保證傳回陣列中的值順序。

程式碼範例

若要檢視使用 $addToSet 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group) 和視窗運算子用量 (在 中$setWindowFields):

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'); // Accumulator usage: collect unique values per group const orders = db.collection('orders'); await 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 } ]); const accumulatorResult = await orders.aggregate([ { $group: { _id: "$customer", cities: { $addToSet: "$city" } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: running set of unique values within each partition const visits = db.collection('visits'); await visits.insertMany([ { _id: 1, customer: "Alice", day: 1, city: "Seattle" }, { _id: 2, customer: "Alice", day: 2, city: "Portland" }, { _id: 3, customer: "Alice", day: 3, city: "Seattle" }, { _id: 4, customer: "Bob", day: 1, city: "Boston" }, { _id: 5, customer: "Bob", day: 2, city: "Boston" } ]); const windowResult = await visits.aggregate([ { $setWindowFields: { partitionBy: "$customer", sortBy: { day: 1 }, output: { citiesSoFar: { $addToSet: "$city", window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); 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'] # Accumulator usage: collect unique values per group orders = db['orders'] orders.insert_many([ { '_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 } ]) accumulator_result = list(orders.aggregate([ { '$group': { '_id': '$customer', 'cities': { '$addToSet': '$city' } } } ])) print('Accumulator result:', accumulator_result) # Window operator usage: running set of unique values within each partition visits = db['visits'] visits.insert_many([ { '_id': 1, 'customer': 'Alice', 'day': 1, 'city': 'Seattle' }, { '_id': 2, 'customer': 'Alice', 'day': 2, 'city': 'Portland' }, { '_id': 3, 'customer': 'Alice', 'day': 3, 'city': 'Seattle' }, { '_id': 4, 'customer': 'Bob', 'day': 1, 'city': 'Boston' }, { '_id': 5, 'customer': 'Bob', 'day': 2, 'city': 'Boston' } ]) window_result = list(visits.aggregate([ { '$setWindowFields': { 'partitionBy': '$customer', 'sortBy': { 'day': 1 }, 'output': { 'citiesSoFar': { '$addToSet': '$city', 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) client.close() example()