user3556159
user3556159

Reputation: 87

MongoDB - insert new document into existing document

I am learning some basics of MongoDB. I have a document from a MongoDB tutorial:

>db.post.insert([
{
   title: 'MongoDB Overview',
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database',
   description: 'NoSQL database doesn't have tables',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 20,
 comments: [
   {
     user:'user1',
     message: 'My first comment',
     dateCreated: new Date(2013,11,10,2,35),
     like: 0
   }
]
}
])

How can I insert a new comment into this existing document ? Thanks

Upvotes: 3

Views: 5911

Answers (2)

John Greenall
John Greenall

Reputation: 1690

Use the $push operator. See mongo docs.

Upvotes: 1

Barno
Barno

Reputation: 3331

You have to use $push

db.coll.update({"title" : "NoSQL Database"},{$push:{"comments":{
     "user":'user2',
     "message": 'My second comment',
     "dateCreated": new Date(2013,11,10,2,35),
     "like": 0
   }}})

Upvotes: 5

Related Questions