$mergeObjects - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$mergeObjects

Amazon DocumentDB 中的$mergeObjects运算符用于将多个文档或对象合并为一个文档。当您需要合并两个或多个文档或对象的内容时,此运算符特别有用,这可能会将一个对象的值与另一个对象的值覆盖。

参数

  • expression1: 第一个要合并的对象。

  • expression2:(可选)要合并的第二个对象。

  • expression3:(可选)要合并的其他对象。

示例(MongoDB 外壳)

以下示例演示如何使用$mergeObjects运算符组合两个对象。

创建示例文档

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