Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-24879

Add $mergeObjects aggregation expression

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major - P3
    • Resolution: Fixed
    • None
    • 3.5.6
    • Aggregation Framework
    • None
    • Fully Compatible
    • Query 2017-03-27, Query 2017-04-17

    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.

      Attachments

        Issue Links

          Activity

            People

              nicholas.zolnierz@mongodb.com Nicholas Zolnierz
              charlie.swanson@mongodb.com Charlie Swanson
              Votes:
              0 Vote for this issue
              Watchers:
              12 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: