$setIntersection - Amazon DocumentDB

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

$setIntersection

$setIntersectionOperator di Amazon DocumentDB digunakan untuk mengembalikan elemen umum antara dua atau lebih array. Operator ini sangat berguna saat bekerja dengan set data, memungkinkan Anda menemukan persimpangan beberapa set.

Parameter

  • array1: Array pertama untuk berpotongan.

  • array2: Array kedua untuk berpotongan.

  • arrayN: (opsional) Array tambahan untuk berpotongan.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan bagaimana menggunakan $setIntersection operator untuk menemukan elemen umum antara dua array.

Buat dokumen sampel

db.collection.insertMany([ { _id: 1, colors: ["red", "blue", "green"] }, { _id: 2, colors: ["blue", "yellow", "orange"] }, { _id: 3, colors: ["red", "green", "purple"] } ])

Contoh kueri

db.collection.aggregate([ { $project: { _id: 1, commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] } } } ])

Keluaran

[ { "_id": 1, "commonColors": ["red", "blue", "green"] }, { "_id": 2, "commonColors": ["blue"] }, { "_id": 3, "commonColors": ["red", "green"] } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan $setIntersection perintah, 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('mycollection'); const result = await collection.aggregate([ { $project: { _id: 1, commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] } } } ]).toArray(); console.log(result); 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['mycollection'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] } } } ])) print(result) client.close() example()