insert in subdocument with mongoDB
Asked Answered
C

1

6

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?

Chavaree answered 31/10, 2013 at 14:46 Comment(1)
this is sub array not subdocument !Ariadne
F
12

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"
   }
 }
});
Franza answered 31/10, 2013 at 22:54 Comment(2)
As far as I'm aware this is currently not an option in Meteor's client side mini-mongo(they haven't implemented the positional operator. It's something they want to have eventually though). This will only work server side. For my apps I've resorted to doing these types of tasks server side. Which is OK but you have to duplicate your security/validation code.Proudhon
they haven't hit 1.0, they're still in preview/development.Proudhon

© 2022 - 2024 — McMap. All rights reserved.