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

$merge operator for updating nested subdocuments

    • Type: Icon: New Feature New Feature
    • Resolution: Won't Do
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Write Ops
    • None
    • Query

      As noted in mongodb-user (https://groups.google.com/d/msg/mongodb-user/7bt38w9RFFU/VmUJQZ0pld0J) it would be useful to have a server-side $merge operator for use when updating documents with nested sub-documents.

      From the group:

      Say I have this object:

      > obj = { "subobj" : { "name": "mysub", "mymap" : { "a" : { "id": "a_obj" },
                                                          "b" : { "id" : "b_obj" },
                                                          "c": {"id": "c_obj" } } } }
      

      And I insert it into my collection:

      > db.xtest.insert(obj)
      

      And now I want to update the "id" of the "b" field in the embedded "mymap".
      I know I can do this with dot notation:

      > db.xtest.update({"_id" : ObjectId("55146d3e497e7087b30da8cf") },
                        { "$set" : { "subobj.mymap.b.id" : "new_b_id" } } )
      

      The dot notation becomes tedious pretty quickly, as you need to write code to flatten the sub-objects to generate the update values. When subobj is complex, the query can become large very quickly.

      This would be a win for consistency and efficiency (presumably a smaller update query would go out over the wire)

      Suggested syntax:

       db.xtest.update({"_id" : ObjectId("55146d3e497e7087b30da8cf") },
                        { "$merge" : { "subobj": {"mymap" : { "a" : { "id": "a_obj" },
                                                          "b" : { "id" : "b_obj" },
                                                          "c": {"id": "c_obj" } } )
      

      Behaviour:

      • Existing values not referenced in the $merge document would be unaffected
      • Values that do not exist in the DB version of the document would be created
      • Values that do exist in the DB version of the document would be updated to the value in the $merge document
      • Atomic operation

            Assignee:
            backlog-server-query Backlog - Query Team (Inactive)
            Reporter:
            david.henderson@triggeredmessaging.com David Henderson
            Votes:
            12 Vote for this issue
            Watchers:
            16 Start watching this issue

              Created:
              Updated:
              Resolved: