$mergeObjects - Amazon DocumentDB

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

$mergeObjects

Amazon DocumentDB の $mergeObjects演算子は、複数のドキュメントまたはオブジェクトを 1 つのドキュメントに結合するために使用されます。この演算子は、2 つ以上のドキュメントまたはオブジェクトの内容をマージする必要があり、あるオブジェクトの値を別のオブジェクトのものと上書きする可能性がある場合に特に便利です。

パラメータ

  • expression1: マージする最初のオブジェクト。

  • expression2: (オプション) マージする 2 番目のオブジェクト。

  • expression3: (オプション) マージする追加のオブジェクト。

例 (MongoDB シェル)

次の例は、 $mergeObjects演算子を使用して 2 つのオブジェクトを組み合わせる方法を示しています。

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

db.collection.insertMany([ { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } }, { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } } ]);

クエリの例

db.collection.aggregate([ { $project: { "combinedAddress": { $mergeObjects: ["$address", { "country": "USA" }] } } } ])

出力

[ { "_id": 1, "combinedAddress": { "city": "New York", "state": "NY", "country": "USA" } }, { "_id": 2, "combinedAddress": { "city": "Los Angeles", "state": "CA", "country": "USA" } } ]

コードの例

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

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('collection'); const result = await collection.aggregate([ { $project: { "combinedAddress": { $mergeObjects: ["$address", { "country": "USA" }] } } } ]).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['collection'] result = list(collection.aggregate([ { '$project': { "combinedAddress": { "$mergeObjects": ["$address", { "country": "USA" }] } } } ])) print(result) client.close() example()