Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to add multiple documents
To add multiple documents to a MongoDB collection efficiently, you can use the insertMany() method for inserting multiple new documents, or bulkWrite() for performing multiple write operations with more control over the insertion process.
Syntax
// Using insertMany()
db.collection.insertMany([
{ field1: "value1", field2: "value2" },
{ field1: "value3", field2: "value4" }
]);
// Using bulkWrite()
db.collection.bulkWrite([
{ "insertOne": { "document": { field1: "value1" } } },
{ "updateOne": { "filter": {}, "update": {}, "upsert": true } }
]);
Method 1: Using insertMany() (Recommended for New Documents)
The simplest way to add multiple documents is with insertMany() ?
db.demo397.insertMany([
{ "Value1": 100, "Value2": 200, "Name": "John" },
{ "Value1": 300, "Value2": 400, "Name": "Alice" },
{ "Value1": 150, "Value2": 250, "Name": "David" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e5e8c07f995e1718151981c"),
"1": ObjectId("5e5e8c07f995e1718151981d"),
"2": ObjectId("5e5e8c07f995e1718151981e")
}
}
Method 2: Using bulkWrite() with Upsert Operations
For more complex operations like conditional inserts or updates, use bulkWrite() ?
const arrayList = [
{ "Value1": 100, "Value2": 200, "Name": "John" },
{ "Value1": 100, "Value2": 200, "Name": "Bob" }
];
let op1 = [];
arrayList.forEach(({ Value1, Value2, Name }) => {
op1.push({
"updateOne": {
"filter": { Name },
"update": { "$set": { Value1, Value2, Name } },
"upsert": true
}
});
});
db.demo397.bulkWrite(op1);
{
"acknowledged": true,
"deletedCount": 0,
"insertedCount": 0,
"matchedCount": 0,
"upsertedCount": 2,
"insertedIds": {},
"upsertedIds": {
"0": ObjectId("5e5e8c07f995e1718151981c"),
"1": ObjectId("5e5e8c07f995e1718151981d")
}
}
Verify Results
Display all documents from the collection ?
db.demo397.find();
{ "_id": ObjectId("5e5e8c07f995e1718151981c"), "Name": "John", "Value1": 100, "Value2": 200 }
{ "_id": ObjectId("5e5e8c07f995e1718151981d"), "Name": "Bob", "Value1": 100, "Value2": 200 }
Key Differences
-
insertMany()- Fast bulk insertion of new documents only -
bulkWrite()- Supports mixed operations (insert, update, delete) with conditional logic -
upsert: true- Inserts document if no match found, updates if match exists
Conclusion
Use insertMany() for simple bulk insertions and bulkWrite() when you need conditional operations or mixed write operations. Both methods provide efficient ways to add multiple documents to MongoDB collections.
Advertisements
