Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert in subdocument with mongoDB

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?

like image 429
Ricklemer Avatar asked Oct 31 '13 14:10

Ricklemer


People also ask

How do I insert a sub file in MongoDB?

Insert a Single Documentdb.collection.insertOne() inserts a single document into a collection. The following example inserts a new document into the inventory collection. If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.

How manually insert data in MongoDB?

To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.


1 Answers

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"
   }
 }
});
like image 104
Salvador Dali Avatar answered Nov 15 '22 16:11

Salvador Dali