MongoDB - Insert Document

insert method ()
To insert data into a MongoDB collection, you need to use the insert() or save() method of MongoDB.
Syntax
The basic syntax of the 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 : 'phpclassroom' , url : 'https://phpclassroom.com' , tags : [ 'mongodb' , 'database' , 'NoSQL' ], likes : 100 })
Here mycol is the name of our collection created in the previous chapter. If the collection does not exist in the database, MongoDB will create the collection and insert the document into it.
In an inserted document, if we don't specify the _id parameter, MongoDB assigns a unique ObjectId for that document.
_id is a 12-byte hexadecimal number that is unique for each document in the collection. 12 bytes are divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
To insert multiple documents in one query, you can pass an array of documents in the insert() command.
example
> db . post . insert ([ { title : 'MongoDB Overview' , description : 'MongoDB is no sql database' , by : 'phpclassroom' , url : 'https://phpclassroom.com' , tags : [ 'mongodb' , ' database' , 'NoSQL' ], likes : 100 }, { title : 'NoSQL Database' , description : "NoSQL database doesn't have tables" , by : 'phpclassroom' , url : 'https://phpclassroom.com' , tags : [ 'mongodb' , 'database ' , 'NoSQL' ], likes : 20 , comments : [ { user : 'user1' , message : 'My first comment', dateCreated : new Date ( 2013 , 11 , 10 , 2 , 35 ), like : 0 } ] } ])
You can also use db.post.save (document) to insert a document . If you don't specify _id in the document, then the save() method will work just like the insert() method . If you specify _id, it will replace all document data containing _id as specified in the save() method.