How to Insert Document in MongoDB ?

The tutorial provides the steps to insert document using MongoDB. A document is inserted in mongodb using insert() , insertOne() , insertMany() methods which we will discuss in detail with examples.

Insert Document in MongoDB

MongoDB stores the data into documents. The below points can be considered for the Insert Document in MongoDB

  • MongoDB allows to insert a single document in a collection
  • MongoDB allows to insert multiple documents in a collection
  • If the collection does not exist, MongoDB will automatically creates the collection
  • Each document in a collection requires a unique field (_id) which represents as the Primary Key for the document. MongoDB generates the ObjectId automatically if the _Id is not provided during the Insert Document
  • MongoDB ensures atomicity for the write operations

What is objectId in MongoDB ?

An ObjectId is :

  • An unique key or id
  • it is faster to generate
  • it has 12 bytes length ( 4 byte – timestamp for objectId creation, 5 byte – random value , 3 byte – incrementing counter)
  • ObjectId creation can be accessed by ObjectId.getTimestamp() method

The Insert Document Methods in MongoDB

Option 1: Insert Document 

Syntax –  db.collectionname.insert(document)

This command is the basic command to insert document where collectionname is the name of the collection, insert is the CRUD Operation for inserting single or multiple document. The below given is the sample for inserting document

> db.oracelappsUsers.insert({
… name: "Mohit Sharma",
… userType: "Admin",
… description: "MongoDB insert document sample",
… createdBy: "oracelappshelp.com"
… })
WriteResult({ "nInserted" : 1 })
>

The inserted record can be validated by the below find command. Although we had not provided the _Id  ( unique value) for the inserted document, but MongoDB automatically creates the _id as given below.

>db.oracelappsUsers.find( { name: "Mohit Sharma" } )
{ "_id" : ObjectId("5f12fd48d4a587e31cddd7e5"), "name" : "Mohit Sharma", "userType" : "Admin", "description" : "MongoDB insert document sample", "createdBy" : "oracelappshelp.com" }

Option 2: Insert Single Document

Syntax – db.collection.insertOne()

This command allows to insert the single document in the collection. The below example illustrates the same.

> try {
… db.oracleappshelpproducts.insertOne( { item: "MongoDBMockTest", qty: 1 } );
… } catch (e) {
… print (e);
… };

MongoDB executes the insertOne() for the single document and returns the acknowledgment with the generated objectId (_Id) value.

{
     "acknowledged" : true,
     "insertedId" : ObjectId("5f1302733a96070d59afd2bf")
}
>

Another example for insertOne() where _id is being provided. MongoDB considers the same _id and returns it back with the acknowledgement for the inserted document.

>try {
… db.oracleappshelpproducts.insertOne( { _id: 21, item: "MongoDBTutorialPDF", qty: 1 } );
… } catch (e) {
… print (e);
… };
{ "acknowledged" : true, "insertedId" : 21 }

Option 2: Insert Multiple Document

Syntax – db.collection.insertMany()

This command allows to insert the multiple document in the collection. The below example illustrates the same.

> try {
… db.oracleappshelpproducts.insertMany(
… [
… { _id: 22, item: "SQLServerTutorialPDF", qty: 1 } ,
… { _id: 23, item: "CouchDBTutorialPDF", qty: 1 },
… { _id: 24, item: "CassandraTutorialPDF", qty: 1 }
… ]);
… } catch (e) {
… print (e);
… };

The below given is the return output by MongoDB for the Bulk Insertion of multiple documents.

{ "acknowledged" : true, "insertedIds" : [ 22, 23, 24 ] }
>

Insert Document Error for Duplicate Key in collection

In case the _Id is repeated for the inserted document , MongoDB returns the Duplicate Key error in the collection as given below.

> try {
db.oracleappshelpproducts.insertMany(
[
{ _id: 21, item: "SQLServerTutorialPDF", qty: 1 } ,
{ _id: 21, item: "CouchDBTutorialPDF", qty: 1 },
{ _id: 21, item: "CassandraTutorialPDF", qty: 1 }
]);
} catch (e) {
print (e);
};

>BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.oracleappshelpproducts index: id dup key: { _id: 21.0 }",
"op" : {
"_id" : 21,
"item" : "SQLServerTutorialPDF",
"qty" : 1
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
How to Insert Document in MongoDB ?
Scroll to top
Copy Protected by Chetan's WP-Copyprotect.