[SERVER-24879] Add $mergeObjects aggregation expression Created: 01/Jul/16  Updated: 08/Aug/17  Resolved: 31/Mar/17

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: 3.5.6

Type: New Feature Priority: Major - P3
Reporter: Charlie Swanson Assignee: Nicholas Zolnierz
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Documented
is documented by DOCS-10316 Docs for SERVER-24879: Add $mergeObje... Closed
Backwards Compatibility: Fully Compatible
Sprint: Query 2017-03-27, Query 2017-04-17
Participants:

 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.


 Comments   
Comment by Githook User [ 31/Mar/17 ]

Author:

{u'username': u'nzolnierzmdb', u'name': u'nzolnierzmdb', u'email': u'nicholas.zolnierz@mongodb.com'}

Message: SERVER-24879 Add $mergeObjects aggregation expression
Branch: master
https://github.com/mongodb/mongo/commit/896687b8ae6b7f848da88c7186a44bf3163c2254

Generated at Thu Feb 08 04:07:40 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.