Add $mergeObjects aggregation expression

XMLWordPrintableJSON

    • Type: New Feature
    • Resolution: Done
    • Priority: Major - P3
    • 3.5.6
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • None
    • Fully Compatible
    • Query 2017-03-27, Query 2017-04-17
    • None
    • 3
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      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.

              Assignee:
              Nicholas Zolnierz
              Reporter:
              Charlie Swanson
              Votes:
              0 Vote for this issue
              Watchers:
              12 Start watching this issue

                Created:
                Updated:
                Resolved: