MongoDB insertMany() Method db.Collection.insertMany() (original) (raw)

**MongoDB **insertMany()**method is a powerful tool for inserting **multiple documents into a collection in one operation. This method is highly **versatile, allowing for both **ordered and **unordered inserts, and provides options for customizing the write concern.

In this article, We will learn about **insertMany() in MongoDB by including its syntax, parameters, return types, and practical examples. Whether we’re working in the MongoDB shell, Node.js, or Python, this guide will help you understand how to use insertMany() effectively for batch document insertion.

What is the MongoDB insertMany() Method?

The insertMany() in **MongoDB is a method that is used to**insert one or more documents in the collection. The **insertMany() in MongoDB takes a list of documents and adds them to the collection. By default, documents are inserted in the given order if we want to insert documents **unordered then set the value of ordered to **false. Using this method we can also create a collection by inserting documents.

We can insert documents with or without **_id field. If we insert a document in the collection without the _id field MongoDB will automatically add an _id field and assign it with a unique **ObjectId. And if we 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.

Key Benefits of insertMany():

**Syntax:

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

Parameters:

  1. <document1>, <document2>, ...: An array of documents to insert into the collection.
  2. writeConcern (optional): A document specifying the write concern to use. If you don’t want to use the default write concern, we can specify it here.
  3. ordered (optional): A boolean value that determines whether the documents are inserted in order. The default is true (ordered insertion). If you want to insert documents unordered, set this value to false.

Return Type of insertMany()

The insertMany() method returns an object that includes:

**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):

  1. **Duplicate Key Errors: Ensure no duplicates in unique indexed fields, and use{ ordered: false }**to continue inserting remaining documents despite errors.
  2. **Validation Errors: Ensure all documents meet schema validation rules.
  3. **Network Issues: Implement retry logic to handle transient network errors.
  4. **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 }
]

Conclusion

Overall, the insertMany method in MongoDB is a powerful tool for inserting multiple documents into a collection. It allows for efficient bulk inserts and provides options for handling errors and controlling the order of insertion. Whether we need to insert a few documents or thousands, insertMany is a reliable and efficient way to add data to your MongoDB collections. By understanding the syntax, parameters, and best practices, you can efficiently manage your MongoDB data.