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
Mass insertion in MongoDB
For mass insertion in MongoDB, use the insertMany() method to insert multiple documents into a collection in a single operation. This is more efficient than inserting documents individually using multiple insert() calls.
Syntax
db.collection.insertMany([
{ document1 },
{ document2 },
{ document3 }
]);
Example
Let us create a collection with multiple bank customer documents ?
db.demo729.insertMany([
{ BankName: "HDFC Bank", cardType: "Credit", "CustomerName": [{Name: "Chris", Age: 25}] },
{ BankName: "ICICI Bank", cardType: "Debit", "CustomerName": [{Name: "Bob", Age: 22}] },
{ BankName: "Kotak Bank", cardType: "Debit", "CustomerName": [{Name: "David", Age: 23}] }
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5eac510d56e85a39df5f6333"),
ObjectId("5eac510d56e85a39df5f6334"),
ObjectId("5eac510d56e85a39df5f6335")
]
}
Verify Result
Display all documents from the collection using the find() method ?
db.demo729.find().pretty();
{
"_id" : ObjectId("5eac510d56e85a39df5f6333"),
"BankName" : "HDFC Bank",
"cardType" : "Credit",
"CustomerName" : [
{
"Name" : "Chris",
"Age" : 25
}
]
}
{
"_id" : ObjectId("5eac510d56e85a39df5f6334"),
"BankName" : "ICICI Bank",
"cardType" : "Debit",
"CustomerName" : [
{
"Name" : "Bob",
"Age" : 22
}
]
}
{
"_id" : ObjectId("5eac510d56e85a39df5f6335"),
"BankName" : "Kotak Bank",
"cardType" : "Debit",
"CustomerName" : [
{
"Name" : "David",
"Age" : 23
}
]
}
Conclusion
The insertMany() method efficiently inserts multiple documents in a single database operation. It returns an acknowledgment with the generated ObjectIds for all inserted documents, making it ideal for bulk data insertion scenarios.
Advertisements
