MongoDB Insert Documents Method

Hari Sapna Nair
Last Updated: May 13, 2022

Introduction 

MongoDB is one of the most popular NoSQL databases. MongoDB data is stored in BSON format as key-value pairs where we define a unique key with a value associated with it. These key-value pairs are then stored in a document, which in turn is stored in a collection

 

Check out the blog Create Database, Collections, and Documents in MongoDB for a better understanding.

 

To add or insert new documents into a collection in the database, we use the MongoDB insert documents method. Let us discuss them in detail. 

MongoDB insert documents: insert() Method

In MongoDB, to insert data into collections, the insert() method is used. The insert() method takes two parameters, the first parameter is the document or array of the document we want to insert, and the remaining are optional.

 

Syntax:

// MongoDB insert document
>db.COLLECTION_NAME.insert(
<document>,
{
  writeConcern: <document>,
  ordered: <boolean>
})

// MongoDB insert documents
>db.COLLECTION_NAME.insert(
<[document1, document2,…]>,
{
  writeConcern: <document>,
  ordered: <boolean>
})

 

Parameters:

Parameter

Description

Type

document

(required)

The document or an array of documents to be inserted into the collection.document/array of documents

writeConcern

(optional)

A document expressing the write concern. It is used when we do not want to use the default write concern. document

ordered

(optional)

If true, performs an ordered insertion of the documents in the array. MongoDB will return without processing the remaining documents in the array if an error occurs with one of the documents.

 

If false, performs an unordered insertion of the documents. And if an error occurs with any one of the documents to be inserted, it continues processing the remaining documents in the array.

boolean


Return:

The insert() method returns WriteResult when a single document is inserted in the collection. And if multiple documents are inserted in the collection, this method returns BulkWriteResult.

MongoDB insert single documents

Let us consider a collection with the name student. MongoDB will create this collection if the student collection doesn't exist in the database and then insert a document.
 

> db.student.insert({name: "Sapna", phoneNumber: "0123456789"})
WriteResult({ "nInserted" : 1 })

 

MongoDB will create the _id field during the insert and assign it a unique ObjectId value if we don't specify the _id parameter. To see the inserted document use the following command:
 

> db.student.find().pretty()
{
   "_id" : ObjectId("61a0aee9a269522c893e0c28"),
   "name" : "Sapna",
   "phoneNumber" : "0123456789"
}

MongoDB insert multiple documents

The following example performs a bulk insertion of two documents by passing an array of documents to the insert()method. The documents in the array need not have the same fields. For instance, the first document in the array has a name and phone number field. But the second document has and has a name and email-id field.
 

> db.student.insert([{name: "Raj", phoneNumber: "9123456780"},{name: "Rahul", emailID: "rahul@gmail.com"}])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})


The collection has the following documents now,


> db.student.find().pretty()
{
   "_id" : ObjectId("61a0aee9a269522c893e0c28"),
   "name" : "Sapna",
   "phoneNumber" : "0123456789"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b4"),
   "name" : "Raj",
   "phoneNumber" : "9123456780"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b5"),
   "name" : "Rahul",
   "emailID" : "rahul@gmail.com"
}

MongoDB insert documents with _id Field

Let us now try inserting a document in the student collection with the _id field.
 

> db.student.insert({_id: "01", name: "Sangeeta", phoneNumber: "9823456710", emailID: "sangeeta@gmail.com"})
WriteResult({ "nInserted" : 1 })

 

The collection gets updated like this,

 

> db.student.find().pretty()
{
   "_id" : ObjectId("61a0aee9a269522c893e0c28"),
   "name" : "Sapna",
   "phoneNumber" : "0123456789"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b4"),
   "name" : "Raj",
   "phoneNumber" : "9123456780"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b5"),
   "name" : "Rahul",
   "emailID" : "rahul@gmail.com"
}
{
   "_id" : "01",
   "name" : "Sangeeta",
   "phoneNumber" : "9823456710",
   "emailID" : "sangeeta@gmail.com"
}

MongoDB insert documents: insertOne() Method

If only one document has to be inserted into a collection, we can use the insertOne() method.

 

Syntax:

> db.COLLECTION_NAME.insertOne(document, { writeConcern: document})

 

Parameters:

It consists of the document parameter and the optional writeConcern parameter.

 

Return:

This method returns the following:

  • A boolean value acknowledged as true if write concern was enabled and false if write concern was disabled.
  • The insertedId field with the _id value of the inserted document.

 

Example:

> db.student.insertOne({name: "Amrith", phoneNumber: "123789345"})
{
   "acknowledged" : true,
   "insertedId" : ObjectId("61a0b72baa0caae96fb98041")
}

MongoDB insert documents: insertMany() Method

If multiple documents have to be inserted into a collection, we can use the insertMany() method and pass an array of documents.
 

Syntax:

> db.COLLECTION_NAME.insertMany([document1, document2,…], { writeConcern: document, ordered: boolean})

 

Parameters:

It consists of the document parameter and the optional parameters: writeConcern and ordered.


Return:

This method returns the following:

  • A boolean value acknowledged as true if write concern was enabled and false if write concern was disabled.
  • The insertedId field with the _id value of the inserted document.

 

Example:

> db.student.insertMany([{name: "Shradha", phoneNumber: "123789543"},{name: "Kiran",emailID: "kiran@gmail.com"}])
{
   "acknowledged" : true,
   "insertedIds" : [
       ObjectId("61a0b9c5aa0caae96fb98042"),
       ObjectId("61a0b9c5aa0caae96fb98043")
   ]
}

MongoDB insert documents: bulk

The latest version of MongoDB (MongoDB 2.6) provides a Bulk() API(Application Programming Interface) that can perform multiple write operations in bulk. In this, multiple operations are grouped into a single request. There are two forms of bulk write requests: ordered or unordered. 

 

In the ordered case, the operations are performed in order. The unordered case is not order-dependent, and the operations can be performed in any order. Generally, the unordered operations are faster. 
 

The followings steps have to be performed to insert a group of documents into the collection:
 

Step 1: Initialize a bulk operation builder.
 

> var bulk = db.student.initializeUnorderedBulkOp();

 

For an ordered operation use db.collection.initializeOrderedBulkOp().

 

Step 2: Add insert operations to the bulk object.
 

> bulk.insert({name: "Simran", phoneNumber: "123321123"});
> bulk.insert({name: "Aman", phoneNumber: "456654456"});
> bulk.insert({_id: "01", name: "Gayathri", phoneNumber: "678678678"});

 

Step 3: Execute the bulk operation.
 

> bulk.execute()


When we call the execute() method on the bulk object, the operations in the list are executed.

 

After the successful insertion of the documents into the collection, this method will return a BulkWriteResult object.
 

2021-11-26T18:02:29.385+0530 E QUERY    [thread1] BulkWriteError: write error at item 2 in bulk operation :
BulkWriteError({
   "writeErrors" : [
       {
           "index" : 2,
           "code" : 11000,
           "errmsg" : "E11000 duplicate key error collection: studentsAPI.student index: _id_ dup key: { : \"01\" }",
           "op" : {
               "_id" : "01",
               "name" : "Gayathri",
               "phoneNumber" : "678678678"
           }
       }
   ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

 

As you can see that only two documents are inserted, and there is an error. The error has occurred as we already have a student with _id field value "01."
 

The final collection contains the following documents,
 

> db.student.find().pretty()
{
   "_id" : ObjectId("61a0aee9a269522c893e0c28"),
   "name" : "Sapna",
   "phoneNumber" : "0123456789"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b4"),
   "name" : "Raj",
   "phoneNumber" : "9123456780"
}
{
   "_id" : ObjectId("61a0b2b80364351976c2b2b5"),
   "name" : "Rahul",
   "emailID" : "rahul@gmail.com"
}
{
   "_id" : "01",
   "name" : "Sangeeta",
   "phoneNumber" : "9823456710",
   "emailID" : "sangeeta@gmail.com"
}
{
   "_id" : ObjectId("61a0b72baa0caae96fb98041"),
   "name" : "Amrith",
   "phoneNumber" : "123789345"
}
{
   "_id" : ObjectId("61a0b9c5aa0caae96fb98042"),
   "name" : "Shradha",
   "phoneNumber" : "123789543"
}
{
   "_id" : ObjectId("61a0b9c5aa0caae96fb98043"),
   "name" : "Kiran",
   "emailID" : "kiran@gmail.com"
}
{
   "_id" : ObjectId("61a0d3dd097e9aba840fbca4"),
   "name" : "Simran",
   "phoneNumber" : "123321123"
}
{
   "_id" : ObjectId("61a0d3dd097e9aba840fbca5"),
   "name" : "Aman",
   "phoneNumber" : "456654456"
}

Frequently Asked Questions

1. What is meant by the upsert operation?

Ans:- Upsert is an operation that performs either an updation of an existing document or an insertion of a new document if the document to modify does not exist.
 

2. What does the nInserted field specify?

Ans:- Th nInserted field specifies the number of documents inserted into the collection.

 

3. How does MongoDB generate the ObjectId?

Ans:- The _id field provided by MongoDB is a 12-byte value of ObjectId. It is prepared from the following values:

  • a 4-byte value denoting the seconds as Unix epoch
  • a 3-byte device identifier value
  • a 2-byte processing id
  • a 3 byte counter which is a random value
     

4. What happens when there is an error during the insertion operation?

Ans:- In the case of any error during the insertion operation, the BulkWriteResult or  WriteResult will specify that error.

Key Takeaways

This blog covered the usage of the MongoDB insert documents methods in detail. The methods discussed in this blog are: inert(), insertOne(), insertMany(), and the bulk operation.

 

Don't stop here. Check out more blogs related to MongoDB. Also, if you are a beginner in MongoDB, go through the 25 Most Common Commands for MongoDB Beginners.

 

We hope you found this blog useful. Liked the blog? Then feel free to upvote and share it.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think