$setIntersection - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$setIntersection

Amazon DocumentDB の $setIntersection演算子は、2 つ以上の配列間の共通要素を返すために使用されます。この演算子は、データセットを操作するときに特に役立ち、複数のセットの交差を見つけることができます。

パラメータ

  • array1: 交差する最初の配列。

  • array2: 交差する 2 番目の配列。

  • arrayN: (オプション) 交差する追加の配列。

例 (MongoDB シェル)

次の例は、 $setIntersection演算子を使用して 2 つの配列間の共通要素を検索する方法を示しています。

サンプルドキュメントを作成する

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

クエリの例

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

出力

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

コードの例

$setIntersection コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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