View a markdown version of this page

$aggiungi ToSet - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$aggiungi ToSet

L'operatore $addToSet di aggregazione restituisce una matrice di valori univoci da un'espressione specificata per ogni gruppo. Viene utilizzato all'interno dello $group stage per accumulare valori distinti, eliminando automaticamente i duplicati.

Parametri

  • expression: L'espressione da valutare per ogni documento del gruppo.

Esempio (MongoDB Shell)

L'esempio seguente dimostra l'utilizzo dell'$addToSetoperatore per raccogliere città uniche in cui sono stati effettuati gli ordini per ciascun cliente.

Crea documenti di esempio

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 } ]);

Esempio di interrogazione

db.orders.aggregate([ { $group: { _id: "$customer", cities: { $addToSet: "$city" } } } ]);

Output

[ { _id: 'Bob', cities: [ 'Seattle', 'Boston' ] }, { _id: 'Alice', cities: [ 'Seattle', 'Portland' ] } ]

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$addToSetoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce una matrice dei valori univoci dell'espressione specificata per i documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Nota

Se utilizzato come operatore di finestra in$setWindowFields, $addToSet è limitato a 100 MB di dati intermedi. Un'operazione che supera questo limite restituisce un errore.

Crea documenti di esempio

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" } ]);

Esempio di interrogazione

L'esempio seguente suddivide i documenti in basecustomer, ordina ogni partizione in base day e restituisce il set di city valori univoci dall'inizio della partizione fino al documento corrente.

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

Output

[ { "_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" ] } ]

Ogni documento è arricchito con citiesSoFar l'insieme di city valori univoci all'interno della sua partizione dall'inizio fino al documento corrente. Come nel modulo accumulatore, l'ordine dei valori nell'array restituito non è garantito.

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo $addToSet dell'operatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (in$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()