定义
将多个文档合并为一个文档。
$mergeObjects 可在以下阶段使用:
语法
When used as a $bucket, $bucketAuto, or $group stage accumulator, $mergeObjects has this syntax:
{ $mergeObjects: <document> }
When used in other expressions (including in $bucket, $bucketAuto, and $group stages) but not as an accumulator, $mergeObjects has this syntax:
{ $mergeObjects: [ <document1>, <document2>, ... ] }
<document> 可以是任何解析为文档的有效表达式。
行为
$mergeObjects ignores null operands. If all the operands to $mergeObjects resolves to null, $mergeObjects returns an empty document { }.
$mergeObjects 会在合并这些文档时覆盖字段值。如果要合并的文档包含相同的字段名称,则生成的文档中的字段将具有该字段合并的最后一个文档中的值。
例子 | 结果 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| | ||||||||
| | ||||||||
| | ||||||||
| |
示例
$mergeObjects
使用以下文档创建集合 orders:
db.orders.insertMany( [ { "_id" : 1, "item" : "abc", "price" : 12, "ordered" : 2 }, { "_id" : 2, "item" : "jkl", "price" : 20, "ordered" : 1 } ] )
再创建一个包含以下文档的集合 items:
db.items.insertMany( [ { "_id" : 1, "item" : "abc", description: "product 1", "instock" : 120 }, { "_id" : 2, "item" : "def", description: "product 2", "instock" : 80 }, { "_id" : 3, "item" : "jkl", description: "product 3", "instock" : 60 } ] )
The following operation first uses the $lookup stage to join the two collections by the item fields and then uses $mergeObjects in the $replaceRoot to merge the joined documents from items and orders:
db.orders.aggregate( [ { $lookup: { from: "items", localField: "item", // field in the orders collection foreignField: "item", // field in the items collection as: "fromItems" } }, { $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } } }, { $project: { fromItems: 0 } } ] )
该操作将返回以下文档:
{ _id: 1, item: 'abc', description: 'product 1', instock: 120, price: 12, ordered: 2 }, { _id: 2, item: 'jkl', description: 'product 3', instock: 60, price: 20, ordered: 1 }
$mergeObjects 作为累加器
使用以下文档创建集合 sales:
db.sales.insertMany( [ { _id: 1, year: 2017, item: "A", quantity: { "2017Q1": 500, "2017Q2": 500 } }, { _id: 2, year: 2016, item: "A", quantity: { "2016Q1": 400, "2016Q2": 300, "2016Q3": 0, "2016Q4": 0 } } , { _id: 3, year: 2017, item: "B", quantity: { "2017Q1": 300 } }, { _id: 4, year: 2016, item: "B", quantity: { "2016Q3": 100, "2016Q4": 250 } } ] )
The following operation uses $mergeObjects as a accumulator in a $group stage that groups documents by the item field:
注意
When used as an accumulator, $mergeObjects operator accepts a single operand.
db.sales.aggregate( [ { $group: { _id: "$item", mergedSales: { $mergeObjects: "$quantity" } } } ] )
该操作将返回以下文档:
{ _id: 'A', mergedSales: { '2017Q1': 500, '2017Q2': 500, '2016Q1': 400, '2016Q2': 300, '2016Q3': 0, '2016Q4': 0 } }, { _id: 'B', mergedSales: { '2017Q1': 300, '2016Q3': 100, '2016Q4': 250 } }
注意
如果要合并的文档包含相同的字段名称,则生成的文档中的该字段将包含合并的最后一个文档中的对应字段值。