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 many insertsupdates without affecting performance?
To perform many inserts and updates in MongoDB without affecting performance, use bulk operations like insertMany() for inserts and proper indexing to optimize query performance. Create indexes on frequently queried fields to speed up both read and write operations.
Syntax
// Bulk insert
db.collection.insertMany([document1, document2, ...]);
// Create index for better performance
db.collection.createIndex({fieldName: 1});
Sample Data
Let us create a collection with multiple documents using insertMany() ?
db.demo325.insertMany([
{ _id: 101, Name: "Chris", Age: 23 },
{ _id: 102, Name: "David", Age: 24 },
{ _id: 103, Name: "Bob", Age: 22 }
]);
{
"acknowledged": true,
"insertedIds": [101, 102, 103]
}
Verify the Data
db.demo325.find().pretty();
{ "_id": 101, "Name": "Chris", "Age": 23 }
{ "_id": 102, "Name": "David", "Age": 24 }
{ "_id": 103, "Name": "Bob", "Age": 22 }
Create Index for Performance
Create an index on the Name field to improve query performance ?
db.demo325.createIndex({Name: 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Key Performance Tips
- Use
insertMany()instead of multipleinsertOne()calls - Create indexes on frequently queried fields before bulk operations
- Use
bulkWrite()for mixed insert/update operations - Consider
ordered: falseoption for parallel processing
Conclusion
Combine insertMany() for bulk inserts with proper indexing using createIndex() to maintain optimal performance. This approach minimizes network roundtrips and leverages MongoDB's efficient bulk operation handling.
Advertisements
