MongoDB : Insert one single document to a collection

MongoDB : Insert one single document to a collection :

For inserting one document to a collection in MongoDB, we can use insertOne() method. It has the following syntax :

db.collection.insertOne(
   ,
   {
      writeConcern: 
   }
)

1. document : It is document type. It is the document we are inserting to the database.
2. writeConcern : It is also document type.It is an optional value used for write concern.

It returns one document that holds the following two values :
1. One boolean acknowledged. It will be true if the write concern was true. Else, it will be false.
2. insertedId with the _id of the inserted document id.

Example of insertOne() :

Let’s try to understand insertOne with a simple example :

db.userList.insertOne(
 	{
 	_id : 1 , 
 	name : "Albert" , 
 	marks : { 
 		physics : 88, 
 		English : 89 
 		} 
 	} 
 )

It will insert one document to the collection and userList and print out the below output :

{ "acknowledged" : true, "insertedId" : 1 }

As we have set the value of _id as 1, the return value contains insertedId with value 1.
MongoDB insertOne

You can also check all documents inserted to the collection using db.userList.find().
MongoDB insertOne

Example to insert multiple documents one by one :

Below example will insert multiple different documents one by one to the collection.

> db.userList.insertOne( {_id : 1 , name : "Albert" , marks : { physics : 88, English : 89 } } )
{ "acknowledged" : true, "insertedId" : 1 }
> db.userList.insertOne( {_id : 2 , name : "Alex" , marks : { physics : 78, English : 59 } } )
{ "acknowledged" : true, "insertedId" : 2 }
> db.userList.insertOne( {_id : 3 , name : "Bob" , marks : { physics : 80, English : 91 } } )
{ "acknowledged" : true, "insertedId" : 3 }

MongoDB insertOne

Conclusion :

insertOne() is a newly introduced method in MongoDB. Previously insert() method was used but currently it is deprecated. insertOne is used mainly for inserting one single document. For multiple documents, insertMany is used. Go through the examples above and drop a comment below if you have any doubt.

Leave a Reply