Insert multiple documents to a MongoDB collection using insertMany

insertMany() in MongoDB :

insertMany() was introduced in MongoDB version 3.2. Using this method, we can insert multiple documents to a collection easily. It has the below syntax :

db.collection.insertMany(
   [  , , ... ],
   {
      writeConcern: ,
      ordered: 
   }
)
  1. document: An array of documents inserting to the collection

  2. writeConcern : Optional document value. It is used to express the write concern.

  3. ordered : Boolean flag to inform if the insert operation should be ordered or unordered.The default value is true.

It will return :

  1. Array of _id for each document that was inserted successfully.
  2. A boolean value acknowledged with result true if the write concern was enabled, else false.

Now, let’s try to implement this with an example :

Example to use insertMany() :

We can either set the value of _id for each document or else _id value is assigned automatically. Let’s take a look at the example below :

db.student.insertMany([{name : "Alex", age : 19}, {name : "Albert" , age : 20}, {name : "Bob" , age : 19}
])

It will print the below output :

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5b680cbc80847beb3aa3e837"),
                ObjectId("5b680cbc80847beb3aa3e838"),
                ObjectId("5b680cbc80847beb3aa3e839")
        ]
}

As you can see that the ids inserted are random values. We can check the content of this collection using db.collection.find()

MongoDB insertMany

Using insertMany with user define _id :

Now, let’s try to insert documents to a collection with _id values specified :

db.users.insertMany([{_id : 1 , name : "Alex" , age : 20}, {_id : 2 , name : "Albert" , age : 21}])

It will print :

{ "acknowledged" : true, "insertedIds" : [ 1, 2 ] }

As you can see that the ids inserted are the same as we have provided. If you check all the documents in the collection, it will give you output like below :

{ "_id" : 1, "name" : "Alex", "age" : 20 }
{ "_id" : 2, "name" : "Albert", "age" : 21 }

MongoDB insertMany One thing you need to make sure that all ids are different in the same collection. Or else, it will throw BulkWriteError:.

Ordered or Unordered insert :

Let’s take a look at the example below :

db.admin.insertMany([{_id : 1 , name : "Alex"}, {_id : 1 , name : "Albert"}, {_id : 2 , name : "Bob"}])

It will throw one error as first two ids are of the same value. Now, if you check the collection, it will contain the following documents :

{ "_id" : 1, "name" : "Alex" }

The exception was thrown on the second element. So, the third element was not inserted. Now, let’s try the same example with ordered value as false :

db.admin.insertMany([{_id : 1 , name : "Alex"}, {_id : 1 , name : "Albert"}, {_id : 2 , name : "Bob"}] ,
{ ordered : false})

It will also throw the same exception. But if you check the collection, it will contain the following documents :

{ "_id" : 1, "name" : "Alex" }
{ "_id" : 2, "name" : "Bob" }

As you can see that even though the exception was raised for the second item, other documents were inserted perfectly.

Conclusion :

We have seen the basic examples of inserting multiple documents to a MongoDB collection using insertMany() and different use cases. Try the examples and drop one comment if you have any queries. Happy coding :)