Open In App
Related Articles

MongoDB insertMany() Method – db.Collection.insertMany()

Like Article
Save Article
Report issue

The insertMany() method inserts one or more documents in the collection. It takes array of documents to insert in the collection. 

  • By default, documents are inserted in the given order if you want to insert documents in unordered, then set the value of ordered to false.
  • Using this method you can also create a collection by inserting documents.
  • You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error.
  • This method can also throw a BulkWriteError exception.
  • This method can also be used inside multi-document transactions.


[<document 1>, <document 2>, ...],
    writeConcern: <document>,
    ordered: <boolean>


  • The first parameter is the array of documents to insert into the collection.
  • The second parameter is optional.

Optional Parameters:

  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • ordered: The type of this parameter is boolean that specifies whether the MongoDB instance should perform an ordered or unordered insertion. If it is true insertion will be in ordered manner otherwise in unordered manner. Default it is true.

Return Type:

This method returns :

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


In the following examples, we are working with:

Database: gfg

Collection: student

Document: Empty

Example 1: Inserts the one document that contains the name and age of the student


Example 2: Insert the array of documents that contains the name and age of the students


Example 3: Insert multiple documents with _id field

db.student.insertMany([{_id:"stu200", name:"Ammu", age:18},
                       {_id:"stu201", name:"Priya", age:29}])

Example 4: Insert unordered documents by setting the value of ordered option to false

                       {_id:"stu202", name:"Priya", age:25}], 
                       {ordered: false})

Last Updated : 05 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads