Insert Document in MongoDB

To insert data into Collection in MongoDB, you need to use the insert () or save () method.

Insert () method in MongoDB

To insert data into Collection in MongoDB, you need to use the insert () or save () method .

Syntax

The basic syntax of insert () is as follows:

 > db . COLLECTION_NAME . insert ( document ) 

For example

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

Here, mycol is the name of the Collection, created in the previous chapter. If this Collection does not already exist in the database, MongoDB will create this Collection and then insert the Document into it.

In the inserted Document, if we do not specify the _id parameter, MongoDB assigns a unique ObjectId to this Document.

_id is a unique hexadecimal number, 12 bytes long for each Document in a Collection. 12 bytes are divided as follows (described in the previous chapters):

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

To insert multiple Documents in a single query, you can pass an array of Documents in the insert () command.

For example

 > 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 } ] } ]) 

To insert data into the Document, you can also use db.post.save (document). If you don't define _id in the Document, the save () method will work like the insert () method. If you specify _id, it will replace the entire data of the Document containing _id when specified in the save () method.

According to Tutorialspoint

Previous article: Data type in MongoDB

Next article: Query Document in MongoDB

4 ★ | 2 Vote