Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: How do I insert another subdocument to an existing document

I've started to learn Mongo. Given the following collection, say called posts, how would I go about inserting a new comment to an already existing document? The examples I've seen on the mongo website are for "simple" collections. Thanks for the help.

{ "_id" : ObjectId( "510a3c5382d395b70b000034" ),

  "authorId" : ObjectId( "..." ),
  "comments" : [ 
    { "_id" : ObjectId( "..." ),
      "authorId" : ObjectId( "..." ),
      "content" : "",
      "createdAt" : Date(...) } ],
  "content" : "Some" } 
like image 932
Harvester316 Avatar asked Oct 15 '13 01:10

Harvester316


People also ask

How do I add a new field in MongoDB?

To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .

How manually insert data in MongoDB?

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


1 Answers

You can try something like this:

    db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
    {
     $push: { comments: { "_id" : ObjectId( "..." ),
     "authorId" : ObjectId( "..." ),
     "content" : "",
     "createdAt" : Date(...) } }
    })
like image 107
Jhanvi Avatar answered Oct 11 '22 21:10

Jhanvi