Table of Contents
Insert Document in Mongodb is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
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 )
As an 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.
As an 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 } ] } ])
FAQ
What should you know about insert () method in MongoDB?
To insert data into Collection in MongoDB, you need to use the insert () or save () method.
What is Insert Document in Mongodb?
Insert () method in MongoDB To insert data into Collection in MongoDB, you need to use the insert () or save () method.
Why is Insert Document in Mongodb important?
A clear understanding of Insert Document in Mongodb helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
Reader Comments 0
Sign in with email or Google to join the discussion.