MongoDB Tutorial - MongoDB Insert Document








To insert data into MongoDB collection, use MongoDB's insert() or save()method.

Syntax

The following code shows the syntax of insert() command:

>db.COLLECTION_NAME.insert(document)

Example

>db.mycol.insert({
   _id: ObjectId(2df22ad2222c),
   title: 'MongoDB Tutorial', 
   description: 'MongoDB is no sql database',
   by: 'java2s.com',
   url: 'http://www.java2s.com',
   tags: ['mongodb', 'database', 'NoSQL','tutorial','big data'],
   likes: 100
})

mycol is the collection name. If the collection doesn't exist, MongoDB will create this collection and then insert document into it.

If we don't specify the _id parameter, then MongoDB assigns an unique ObjectId for this document.

>db.post.insert([
{
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   url: 'http://www.java2s.com',
   tags: ['mongodb', 'database', 'NoSQL','tutorial','big data'],
   likes: 122
},
{
   title: 'MongoDB setup', 
   description: 'NoSQL database is schema less',
   url: 'http://www.java2s.com',
   tags: ['mongodb', 'database', 'NoSQL','tutorial','big data'],
   likes: 22, 
   comments: [  
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2014,10,10,2,35),
         like: 0 
      }
   ]
}
])

To insert the document you can use db.post.save(document) also.