$addToSet - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$addToSet

Operator $addToSet agregasi mengembalikan array nilai unik dari ekspresi tertentu untuk setiap grup. Ini digunakan dalam $group tahap untuk mengakumulasi nilai yang berbeda, secara otomatis menghilangkan duplikat.

Parameter

  • expression: Ekspresi untuk mengevaluasi setiap dokumen dalam grup.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan penggunaan $addToSet operator untuk mengumpulkan kota-kota unik di mana pesanan ditempatkan untuk setiap pelanggan.

Buat dokumen sampel

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

Contoh kueri

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

Keluaran

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

Contoh kode

Untuk melihat contoh kode untuk menggunakan operator $addToSet agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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()