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" }
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 .
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
You can try something like this:
db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
{
$push: { comments: { "_id" : ObjectId( "..." ),
"authorId" : ObjectId( "..." ),
"content" : "",
"createdAt" : Date(...) } }
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With