9

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" } 
Harvester316
  • 381
  • 1
  • 8
  • 17
  • See the docs for the available array operators you can use with `update`: http://docs.mongodb.org/manual/reference/operator/update/#array – JohnnyHK Oct 15 '13 at 03:05

1 Answers1

15

You can try something like this:

    db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
    {
     $push: { comments: { "_id" : ObjectId( "..." ),
     "authorId" : ObjectId( "..." ),
     "content" : "",
     "createdAt" : Date(...) } }
    })
Jhanvi
  • 5,069
  • 8
  • 32
  • 41
  • 2
    Thanks. Here's some code again that works for anyone interested. `db.posts.update({ _id: ObjectId("5121908755734d2f29000123") }, { $push: { comments: { "authorId" : ObjectId("50d013076a2208d3060000a7"), "content" : "Some content again" } } })` – Harvester316 Oct 17 '13 at 04:18