View a markdown version of this page

$tambahkan ToSet - Amazon DocumentDB

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

$tambahkan ToSet

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 untuk setiap dokumen dalam grup.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan penggunaan $addToSet operator untuk mengumpulkan kota unik tempat 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 penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$addToSetOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan array nilai unik dari ekspresi yang ditentukan untuk dokumen di setiap jendela. Anda menentukan operator di bawah output bidang, dan secara opsional menentukan batas jendela dengan window dokumen.

catatan

Ketika digunakan sebagai operator jendela di$setWindowFields, $addToSet dibatasi hingga 100 MB data perantara. Operasi yang melebihi batas ini mengembalikan kesalahan.

Buat dokumen sampel

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

Contoh kueri

Contoh berikut mempartisi dokumen berdasarkancustomer, mengurutkan setiap partisi berdasarkanday, dan mengembalikan set city nilai unik dari awal partisi melalui dokumen saat ini.

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

Keluaran

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

Setiap dokumen ditambah dengancitiesSoFar, set city nilai unik dalam partisinya dari awal hingga dokumen saat ini. Seperti bentuk akumulator, urutan nilai dalam array yang dikembalikan tidak dijamin.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $addToSet operator, pilih tab untuk bahasa yang ingin Anda gunakan. Contoh berikut menunjukkan penggunaan akumulator (in$group) dan penggunaan operator jendela (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()