Bulk Writes
When you have many changes to make, sending them one by one costs a network round trip each. bulkWrite() sends a whole list of write operations, of different kinds, in a single call:
db.collection.bulkWrite([
{ insertOne: { document: { … } } },
{ updateOne: { filter: { … }, update: { … }, upsert: false } },
{ updateMany: { filter: { … }, update: { … } } },
{ replaceOne: { filter: { … }, replacement: { … } } },
{ deleteOne: { filter: { … } } },
{ deleteMany: { filter: { … } } }
], { ordered: true })A first bulk write
A supplier delivery arrives: one new product, two restocks and a discontinued item. One bulkWrite handles all of it:
const result = db.products.bulkWrite([
{ insertOne: { document: { _id: 21, name: 'Kenya AA', category: 'coffee', price: 26, stock: 20, tags: ['light'] } } },
{ updateOne: { filter: { _id: 4 }, update: { $inc: { stock: 24 } } } },
{ updateOne: { filter: { _id: 8 }, update: { $inc: { stock: 40 } } } },
{ deleteOne: { filter: { _id: 14 } } }
]);
print(result);
db.products.find({ _id: { $in: [4, 8, 14, 21] } }, { name: 1, stock: 1 }).forEach(p => print(p));{
acknowledged: true,
insertedCount: 1,
insertedIds: { '0': 21 },
matchedCount: 2,
modifiedCount: 2,
deletedCount: 1,
upsertedCount: 0,
upsertedIds: {}
}
{ _id: 4, name: 'Colombia Supremo', stock: 24 }
{ _id: 8, name: 'Chamomile Calm', stock: 40 }
{ _id: 21, name: 'Kenya AA', stock: 20 }
The result adds up the counts of every operation.
Ordered and unordered
Like insertMany, a bulk write is ordered by default: operations run in sequence and the first error stops the rest. With { ordered: false } the server may run them in any order (often faster) and continues after errors:
const ops = [
{ insertOne: { document: { _id: 'x1' } } },
{ insertOne: { document: { _id: 'x1' } } }, // duplicate key
{ insertOne: { document: { _id: 'x2' } } }
];
try { db.ordered.bulkWrite(ops); } catch (err) { print('ordered: inserted', err.result.insertedCount); }
try { db.unordered.bulkWrite(ops, { ordered: false }); } catch (err) { print('unordered: inserted', err.result.insertedCount); }
print(db.ordered.countDocuments(), db.unordered.countDocuments());ordered: inserted 1
unordered: inserted 2
1 2
Building operations from data
Bulk writes shine when the operations come from a file or an API. Here a price list from a supplier is turned into one update per row, with upserts so that new products are created:
const priceList = [
{ sku: 'BEAN-ESP', price: 25 },
{ sku: 'BEAN-HOU', price: 18.5 },
{ sku: 'BEAN-NEW', price: 30 }
];
db.supplier_prices.insertMany([
{ _id: 'BEAN-ESP', price: 24 },
{ _id: 'BEAN-HOU', price: 18.5 }
]);
const res = db.supplier_prices.bulkWrite(priceList.map(row => ({
updateOne: { filter: { _id: row.sku }, update: { $set: { price: row.price } }, upsert: true }
})));
print('matched', res.matchedCount, 'modified', res.modifiedCount, 'upserted', res.upsertedCount);
print(db.supplier_prices.find().sort({ _id: 1 }).toArray());matched 2 modified 1 upserted 1
[
{ _id: 'BEAN-ESP', price: 25 },
{ _id: 'BEAN-HOU', price: 18.5 },
{ _id: 'BEAN-NEW', price: 30 }
]
BEAN-HOU matched but wasn't modified because its price was already 18.5.
Bulk writes are not transactions
Each operation in a bulk write is atomic on its own document, but the batch as a whole is not: if operation 3 fails, operations 1 and 2 stay applied. When several changes must succeed or fail together, use a transaction.
Tip: Drivers split very large batches into chunks automatically (the server accepts up to 100,000 operations per batch), so you can pass a big array without worrying about limits.
Test yourself
What is the main benefit of bulkWrite over many separate calls?
- It is a transaction
- It needs only one round trip for many operations
- It ignores validation
- It creates indexes
In an ordered bulkWrite, operation 2 of 5 fails. What happens to operations 3–5?
- They run anyway
- They are not executed
- They run before operation 2
- Operation 1 is rolled back and the rest run