$setUnion - Amazon DocumentDB

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

$setUnion

Amazon DocumentDB の$setUnion集計演算子は、2 つ以上の値のセットを組み合わせて、入力セットのすべての一意の要素を含むセットを返すために使用されます。この演算子は、ドキュメントの配列フィールドに対してセットベースのオペレーションを実行する必要がある場合に便利です。

パラメータ

  • expression1: 配列に解決される式。

  • expression2: 配列に解決される式。

  • expressionN: 配列に解決される追加の式 (オプション)。

例 (MongoDB シェル)

次の例は、 $setUnion演算子を使用して、コレクション内の 2 つの配列フィールドの一意の要素を組み合わせる方法を示しています。

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

db.users.insertMany([ { _id: 1, name: "Alice", hobbies: ["reading", "swimming"], skills: ["coding", "writing"] }, { _id: 2, name: "Bob", hobbies: ["cooking", "gardening"], skills: ["coding", "photography"] }, { _id: 3, name: "Charlie", hobbies: ["reading", "painting"], skills: ["gardening", "music"] } ]);

クエリの例

db.users.aggregate([ { $project: { name: 1, allInterests: { $setUnion: ["$hobbies", "$skills"] } } } ]);

出力

[ { "_id" : 1, "name" : "Alice", "allInterests" : [ "coding", "reading", "swimming", "writing" ] }, { "_id" : 2, "name" : "Bob", "allInterests" : [ "coding", "cooking", "gardening", "photography" ] }, { "_id" : 3, "name" : "Charlie", "allInterests" : [ "gardening", "music", "painting", "reading" ] } ]

この例では、 $setUnion演算子を使用して、各ユーザードキュメントの hobbiesおよび skills配列フィールドの一意の要素を組み合わせます。結果のallInterestsフィールドには、各ユーザーのすべての固有の趣味とスキルの結合が含まれます。

コードの例

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

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 users = db.collection('users'); const result = await users.aggregate([ { $project: { _id: 1, name: 1, allInterests: { $setUnion: ["$hobbies", "$skills"] } } } ]).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'] users = db['users'] result = list(users.aggregate([ { '$project': { '_id': 1, 'name': 1, 'allInterests': { '$setUnion': ["$hobbies", "$skills"] } } } ])) print(result) client.close() example()