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.
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():_id
if one is not provided.BulkWriteError
.Parameters:db.Collection_name.insertMany(
[<document 1>, <document 2>, ...],
{
writeConcern: <document>,
ordered: <boolean>
})
<document1>, <document2>, ...
: An array of documents to insert into the collection.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.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
.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.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.
In this example, we insert a single document with the name "Akshay" and age 18.
Query:
db.student.insertMany([{name:"Akshay",age:18}])
Output:
[Example 2: Insert Multiple Documents in a Single Operation
{
_id: ObjectId('666c54daada2c128588bf203'),
name: 'Akshay',
age: 18
}
]
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.
_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.
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.
_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
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):
{ ordered: false }
to continue inserting remaining documents despite errors.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 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:
[Conclusion
{
_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 }
]
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4