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 bulk insert for documents
MongoDB provides multiple methods for bulk inserting documents efficiently. The most common approaches are using initializeUnorderedBulkOp() for legacy bulk operations and insertMany() for modern bulk inserts.
Syntax
// Legacy Bulk Operation var bulkOp = db.collection.initializeUnorderedBulkOp(); bulkOp.insert(document1); bulkOp.insert(document2); bulkOp.execute(); // Modern Approach db.collection.insertMany([document1, document2, document3]);
Method 1: Using initializeUnorderedBulkOp()
Create a bulk operation and insert multiple documents ?
var manyDocument = db.demo255.initializeUnorderedBulkOp();
manyDocument.insert({ "Name": "Chris", "Age": 24 });
manyDocument.insert({ "Name": "Bob", "Age": 22 });
manyDocument.insert({ "Name": "David", "Age": 23 });
manyDocument.execute();
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Method 2: Using insertMany() (Recommended)
The modern and simpler approach for bulk insert ?
db.demo255.insertMany([
{ "Name": "Alice", "Age": 25 },
{ "Name": "John", "Age": 28 },
{ "Name": "Sarah", "Age": 26 }
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e47a25e1627c0c63e7dba85"),
ObjectId("5e47a25e1627c0c63e7dba86"),
ObjectId("5e47a25e1627c0c63e7dba87")
]
}
Verify Results
Display all documents from the collection ?
db.demo255.find();
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba82"), "Name" : "Chris", "Age" : 24 }
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba83"), "Name" : "Bob", "Age" : 22 }
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba84"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba85"), "Name" : "Alice", "Age" : 25 }
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba86"), "Name" : "John", "Age" : 28 }
{ "_id" : ObjectId("5e47a25e1627c0c63e7dba87"), "Name" : "Sarah", "Age" : 26 }
Key Differences
-
insertMany()is simpler and recommended for most use cases -
initializeUnorderedBulkOp()provides more control over bulk operations and error handling - Both methods significantly improve performance compared to individual inserts
Conclusion
Use insertMany() for straightforward bulk inserts or initializeUnorderedBulkOp() when you need advanced bulk operation control. Both approaches efficiently insert multiple documents in a single database round trip.
Advertisements
