Documentation Request Summary:
New aggregation expression (that's also an accumulator).
Engineering Ticket Description:
Syntax
{$mergeObjects: [<expression 1>, <expression 2>, ..., <expression N>]}
|
Examples
// 1. Merging two objects together
|
db.merging.insert({_id: 0, subObject: {b: 1, c: 1}})
|
db.merging.aggregate([{$project: {newDocument: {$mergeObjects: ["$subObject", {d: 1}]}}}]);
|
// Results:
|
{_id: 0, newDocument: {b: 1, c: 1, d: 1}}
|
|
// 2. Merging the root with a new field
|
db.merging.insert({_id: 0, field0: 0, field1: 1})
|
db.merging.aggregate([{$project: {newDocument: {$mergeObjects: ["$$ROOT", {newField: "newValue"}]}}}]);
|
// Results:
|
{_id: 0, newDocument: {_id: 0, field0: 0, field1: 1, newField: "newValue"}}
|
|
// 3. Replacing a field in the root.
|
db.merging.insert({_id: 0, field0: 0, field1: 1})
|
db.merging.aggregate([{$project: {newDocument: {$mergeObjects: ["$$ROOT", {field0: "newValue"}]}}}]);
|
// Results:
|
{_id: 0, newDocument: {_id: 0, field0: "newValue", field1: 1}}
|
|
// 4. Overriding in the opposite order
|
db.merging.insert({_id: 0, field0: 0, field1: 1})
|
db.merging.aggregate([{$project: {newDocument: {$mergeObjects: [{field0: "defaultValue"}, "$$ROOT"]}}}]);
|
// Results:
|
{_id: 0, newDocument: {_id: 0, field0: 0, field1: 1}}
|
|
db.merging.insert({_id: 0, field0: 0, subdoc: {a: 1, b: 3}})
|
db.merging.aggregate([{$replaceRoot: {newRoot: {$mergeObjects: ["$$ROOT", "$subdoc"]}}}])
|
// results:
|
{_id: 0, field0: 0, subdoc: {a: 1, b: 3}, a: 1, b: 3}
|
Detailed Behavior
- The new expression will take any number of expressions
- It will error if any expression does not evaluate to an object
- If the field "x" exists in multiple objects, the value of "x" in the last document will win. Since it's an array, you can reverse the order if you wanted different overriding semantics.
|