Question

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" } 
Was it helpful?

Solution

You can try something like this:

    db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
    {
     $push: { comments: { "_id" : ObjectId( "..." ),
     "authorId" : ObjectId( "..." ),
     "content" : "",
     "createdAt" : Date(...) } }
    })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top