Question

I have the following document in the collection:

"_id" : "2",
"workspace" : [{
        "name" : "1",
        "widgets" : [ ]
    },{
        "name" : "2",
        "widgets" : [ ]
    },{
        "name" : "3",
        "widgets" : [ ]
    },{
        "name" : "4",
        "widgets" : [ ]
    }
]}

How can I insert {id: "1", blabla: "blabla"} in "widgets" for the "name" 3?

Was it helpful?

Solution

In comparison to a previous answer which just inserts everything into the root of the document, here is a correct way to do this with positional operator:

db.t.update({
 "_id" : "2",
 "workspace.name" : "3"
},{
 $push: {
   'workspace.$.widgets' : {
       id: "2",
       blabla: "blabla"
   }
 }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top