0
0
MongoDBquery~5 mins

Bulk write operations in MongoDB

Choose your learning style9 modes available
Introduction
Bulk write operations let you do many changes to a database at once. This saves time and makes your work faster.
When you want to add many new items to a list in the database quickly.
When you need to update several records at the same time.
When you want to delete many entries without doing it one by one.
When you want to mix adding, updating, and deleting in one go.
When you want to keep your database changes organized and efficient.
Syntax
MongoDB
db.collection.bulkWrite([
  { insertOne: { document: { /* data */ } } },
  { updateOne: { filter: { /* condition */ }, update: { /* changes */ } } },
  { deleteOne: { filter: { /* condition */ } } },
  { replaceOne: { filter: { /* condition */ }, replacement: { /* new data */ } } }
])
Each operation is an object inside the array passed to bulkWrite.
You can mix different operations like insertOne, updateOne, deleteOne, and replaceOne.
Examples
This example adds Alice, updates Bob's age, and deletes Charlie in one bulk operation.
MongoDB
db.users.bulkWrite([
  { insertOne: { document: { name: "Alice", age: 25 } } },
  { updateOne: { filter: { name: "Bob" }, update: { $set: { age: 30 } } } },
  { deleteOne: { filter: { name: "Charlie" } } }
])
This replaces the product with sku '123' with new data.
MongoDB
db.products.bulkWrite([
  { replaceOne: { filter: { sku: "123" }, replacement: { sku: "123", name: "New Product", price: 20 } } }
])
Sample Program
This bulk operation adds a pen, updates the quantity of notebook, and deletes eraser from inventory.
MongoDB
db.inventory.bulkWrite([
  { insertOne: { document: { item: "pen", qty: 50 } } },
  { updateOne: { filter: { item: "notebook" }, update: { $set: { qty: 100 } } } },
  { deleteOne: { filter: { item: "eraser" } } }
])
OutputSuccess
Important Notes
Bulk operations are faster than doing many single operations one by one.
If one operation fails, others still run unless you use ordered:true to stop on errors.
Use bulkWrite to keep your database changes neat and efficient.
Summary
Bulk write operations let you do many database changes at once.
You can insert, update, delete, or replace many records in one call.
This saves time and keeps your database work organized.