Open In App

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

Last Updated : 24 Sep, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

The insertMany() method in MongoDB adds multiple documents to a collection at once. It is faster and more efficient than inserting documents one by one, making it ideal for handling large sets of data.

Syntax:

db.Collection_name.insertMany(
[<document 1>, <document 2>, ...],
{
    writeConcern: <document>,
    ordered: <boolean>
})

In the above syntax:

  • <document1>, <document2>, … : Array of documents to insert.
  • writeConcern (optional): Overrides the default write concern.
  • ordered (optional): true inserts in order (default); set false for unordered inserts.

Return Type of insertMany()

The insertMany() method returns an object that includes:

  • acknowledged: A boolean that is true if the write concern was enabled, and false if it was disabled.
  • insertedIds: An object containing the _id values of the inserted documents.

Examples of Using insertMany() in MongoDB

To understand insertmany in mongoDB we need a collection on which we will perform various operations and queries. In these examples, we’ll assume we’re working with a collection called student, which contains information about students such as their name and age.

Example 1: Insert a Single Document with insertMany()

In this example, we insert a single document with the name "Akshay" and age 18.

Query:

db.student.insertMany([{name:"Akshay",age:18}])

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
}
]

Example 2: Insert Multiple Documents in a Single Operation

Here, we insert the array of documents that contains the name and age of the students

Query:

db.student.insertMany([{name:"Ajay",age:20},
{name:"Bina",age:24},
{name:"Ram",age:23}])

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
},
{ _id: ObjectId('666c5504ada2c128588bf204'), name: 'Ajay', age: 20 },
{ _id: ObjectId('666c5504ada2c128588bf205'), name: 'Bina', age: 24 },
{ _id: ObjectId('666c5504ada2c128588bf206'), name: 'Ram', age: 23 }
]

Explanation: In this example, three documents are inserted into the student collection in a single operation.

Example 3: Insert Several Document Specifying an _id Field

The query inserts multiple documents into the student collection with manually specified _id values ("stu200", "stu201"), ensuring they remain unique. If a duplicate _id exists, MongoDB throws a duplicate key error.

Query:

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

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
},
{ _id: ObjectId('666c5504ada2c128588bf204'), name: 'Ajay', age: 20 },
{ _id: ObjectId('666c5504ada2c128588bf205'), name: 'Bina', age: 24 },
{ _id: ObjectId('666c5504ada2c128588bf206'), name: 'Ram', age: 23 },
{ _id: 'stu200', name: 'Ammu', age: 18 },
{ _id: 'stu201', name: 'Priya', age: 29 }
]

Explanation: The documents are inserted successfully with the given _id, preventing automatic ObjectId generation. If _id is duplicated, MongoDB will reject the insert operation for that document.

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

By default, insertMany() performs an ordered insert. However, if we want MongoDB to insert documents in an unordered fashion (i.e., documents can be inserted out of sequence), you can set the ordered parameter to false

Query:

db.student.insertMany(
[
{_id:"stu203",name:"Soniya",age:28},
{_id:"stu202", name:"Priya", age:25}],
{ordered: false}
)

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
},
{ _id: ObjectId('666c5504ada2c128588bf204'), name: 'Ajay', age: 20 },
{ _id: ObjectId('666c5504ada2c128588bf205'), name: 'Bina', age: 24 },
{ _id: ObjectId('666c5504ada2c128588bf206'), name: 'Ram', age: 23 },
{ _id: 'stu200', name: 'Ammu', age: 18 },
{ _id: 'stu201', name: 'Priya', age: 29 },
{ _id: 'stu203', name: 'Soniya', age: 28 },
{ _id: 'stu202', name: 'Priya', age: 25 }
]

Explanation: Setting ordered: false ensures that MongoDB doesn’t stop inserting the remaining documents if one document insertion fails.

Example 5: Insert Several Document without Specifying an _id Field

The query inserts multiple documents into the student collection without specifying _id values. MongoDB automatically assigns a unique ObjectId to each document to ensure uniqueness and maintain data integrity.

Query:

db.student.insertMany([
{ name: 'John', age: 22 },
{ name: 'Emily', age: 21 },
{ name: 'Michael', age: 23 },
{ name: 'Sophia', age: 20 }
])

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
},
{ _id: ObjectId('666c5504ada2c128588bf204'), name: 'Ajay', age: 20 },
{ _id: ObjectId('666c5504ada2c128588bf205'), name: 'Bina', age: 24 },
{ _id: ObjectId('666c5504ada2c128588bf206'), name: 'Ram', age: 23 },
{ _id: 'stu200', name: 'Ammu', age: 18 },
{ _id: 'stu201', name: 'Priya', age: 29 },
{ _id: 'stu203', name: 'Soniya', age: 28 },
{ _id: 'stu202', name: 'Priya', age: 25 },
{ _id: ObjectId('666c5712ada2c128588bf20f'), name: 'John', age: 22 },
{ _id: ObjectId('666c5712ada2c128588bf210'), name: 'Emily', age: 21 },
{
_id: ObjectId('666c5712ada2c128588bf211'),
name: 'Michael',
age: 23
},
{
_id: ObjectId('666c5712ada2c128588bf212'),
name: 'Sophia',
age: 20
}
]

Explanation: Each inserted document receives a system-generated ObjectId, ensuring unique identification. The documents are successfully added to the collection without requiring manual _id assignment

Error Handling

When performing bulk operations like insertMany(), errors can occur. MongoDB will throw a BulkWriteError if there’s an issue with one or more documents (for example, a duplicate _id). We can catch these errors using a try-catch block in our application code (e.g., in Node.js):

  • Duplicate Key Errors: Ensure no duplicates in unique indexed fields, and use { ordered: false } to continue inserting remaining documents despite errors.
  • Validation Errors: Ensure all documents meet schema validation rules.
  • Network Issues: Implement retry logic to handle transient network errors.
  • Error Handling: Examine error details to understand and address specific issues.
db.collection.insertMany(docs, { ordered: false })
.then(result => console.log(result))
.catch(error => {
if (error.name === "BulkWriteError") {
error.writeErrors.forEach(writeError => {
console.error("Document index:", writeError.index);
console.error("Error message:", writeError.errmsg);
});
} else {
console.error("Unexpected error:", error);
}
});

This approach helps identify and handle BulkWriteError effectively.

Unordered Inserts

Unordered inserts allow MongoDB to continue inserting documents even if some documents fail to insert. This is useful when we want to insert multiple documents and don't want the entire operation to stop if one document causes an error. To perform unordered inserts, we can use the insertMany method in MongoDB with the ordered option set to false.

Query:

db.students.insertMany(
[
{ name: 'Raj', age: 21 },
{ name: 'Sara', age: 22 },
{ name: 'Tom', age: 23 },
{ name: 'Lisa', age: 24 }
],
{ ordered: false }
)

Output:

[
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
},
{ _id: ObjectId('666c5504ada2c128588bf204'), name: 'Ajay', age: 20 },
{ _id: ObjectId('666c5504ada2c128588bf205'), name: 'Bina', age: 24 },
{ _id: ObjectId('666c5504ada2c128588bf206'), name: 'Ram', age: 23 },
{ _id: 'stu200', name: 'Ammu', age: 18 },
{ _id: 'stu201', name: 'Priya', age: 29 },
{ _id: 'stu203', name: 'Soniya', age: 28 },
{ _id: 'stu202', name: 'Priya', age: 25 },
{ _id: ObjectId('666c5712ada2c128588bf20f'), name: 'John', age: 22 },
{ _id: ObjectId('666c5712ada2c128588bf210'), name: 'Emily', age: 21 },
{
_id: ObjectId('666c5712ada2c128588bf211'),
name: 'Michael',
age: 23
},
{
_id: ObjectId('666c5712ada2c128588bf212'),
name: 'Sophia',
age: 20
},
{ _id: ObjectId('666c5940ada2c128588bf217'), name: 'Raj', age: 21 },
{ _id: ObjectId('666c5940ada2c128588bf218'), name: 'Sara', age: 22 },
{ _id: ObjectId('666c5940ada2c128588bf219'), name: 'Tom', age: 23 },
{ _id: ObjectId('666c5940ada2c128588bf21a'), name: 'Lisa', age: 24 }
]


Explore