Insert Document in MongoDB's Collection



We can use insert() or save() methods to insert document(data) in  collection MongoDB.
Syntax                                                                                                               
Basic syntax of insert() command is as follows:


>db.COLLECTION_NAME.insert(document)


Example


>db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview',
   description: 'MongoDB is no sql database',
   by: 'Codefari',
   url: 'http://www.codefari.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})


mycol is collection name, MongoDB will create collection if doesn't exist in the database then insert document into it. to know how to create collection click here.
if we did not specify the _id parameter, MongoDB assign a unique Object_Id for this document. _id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows:


_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)


If we want to insert multiple documents in single query, then we will be pass an array of document in insert() command.

Example


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



we can use  this way also to insert the document use db.post.save(document). Save () method will work same as insert() method when we did not specify_id in the document. When we have specify _id then it will replace whole data of document containing _id as specified in save() method.

Commentaires