Search code examples
mongodbnesteddocuments

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" } 

Solution

  • You can try something like this:

        db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
        {
         $push: { comments: { "_id" : ObjectId( "..." ),
         "authorId" : ObjectId( "..." ),
         "content" : "",
         "createdAt" : Date(...) } }
        })