Each earlier lesson's insert, update, and delete operations run one at a time — fine for a handful of documents, but a real cost when hundreds or thousands need changing. bulkWrite() batches many operations into a single request to the database.
db.products.bulkWrite([
{ insertOne: { document: { name: 'Widget', price: 9.99 } } },
{ updateOne: {
filter: { name: 'Gadget' },
update: { $set: { price: 14.99 } }
} },
{ deleteOne: { filter: { name: 'Discontinued Item' } } },
])| Operation | Same as |
|---|---|
| insertOne | db.collection.insertOne() |
| updateOne / updateMany | db.collection.updateOne() / updateMany() |
| replaceOne | db.collection.replaceOne() |
| deleteOne / deleteMany | db.collection.deleteOne() / deleteMany() |
Each individual insertOne()/updateOne() call is its own round trip to the database server. bulkWrite() sends every operation together, cutting network overhead dramatically for a large batch.
// Default: ordered — stops at the first failure, operations after it don't run
db.products.bulkWrite([ /* ... */ ])
// Unordered — keeps going even if one operation fails, runs them faster
// (not guaranteed to run in the array's order) since they don't depend on each other
db.products.bulkWrite([ /* ... */ ], { ordered: false })const result = db.products.bulkWrite([ /* ... */ ])
print(result.insertedCount)
print(result.modifiedCount)
print(result.deletedCount)The classic bulkWrite use case
A common real use: importing a CSV or JSON file of thousands of records — read the file, build one bulkWrite() array of insertOne operations, and send it as a single batch instead of thousands of individual inserts.