My collection has many levels of embedded documents in each document. I was writing code to update a document using the C++ API (legacy) and am running into a problem. It is probably easiest to demonstrate what I am hoping to do with the mongo shell.
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") },
Is there anyway to do this WITHOUT dot notation? This does NOT work:
> db.xtest.update({"_id" : ObjectId("55146d3e497e7087b30da8cf") },
{ "$set" : { "subobj" : "mymap" : { "b" : { "id" : "new_b_id" } } } })
It just replaces the document with the exact contents of the update.
I was really hoping there was a "$merge" operation that would work this way so that I could do this:
> db.xtest.update({"_id" : ObjectId("55146d3e497e7087b30da8cf") },
{ "$merge" : { "subobj" : "mymap" : { "b" : { "id" : "new_b_id" } } } })
It would simply merge in new fields and leave existing ones alone.
The reason I wanted to do this was that in the C++ code I was building up a hiearchy of BSON objects to use for the update using recursive calls and the $merge method would work naturally. Having to convert all the updated values to "dot" notation would make the update object much longer and uglier.
But if "dot" notation is all there is, then I guess I will just have to do that.
-Thanks, Derek