Working with Bulk Operations
1. Using bulkWrite() Method
| Aspect | Detail |
|---|---|
| Signature | coll.bulkWrite(operations, options) |
| Operations | Array of {insertOne|updateOne|updateMany|replaceOne|deleteOne|deleteMany} |
| Returns | BulkWriteResult: counts + upsertedIds + insertedIds |
| Server batch | Driver splits into batches ≤ 100k ops / 48MB |
2. Performing insertOne in Bulk
| Form | Result |
|---|---|
{ insertOne: { document: {...} } } | One insert per op |
| Auto _id | Generated if missing |
3. Performing updateOne in Bulk
| Field | Description |
|---|---|
| filter | Selection |
| update | Operators or pipeline |
| upsert | Optional bool |
| collation | Optional |
| arrayFilters | Optional |
| hint | Force index |
4. Performing updateMany in Bulk
| Aspect | Detail |
|---|---|
| Form | { updateMany: { filter, update } } |
| Atomicity | Per document |
| Retryable | No |
5. Performing deleteOne in Bulk
| Aspect | Detail |
|---|---|
| Form | { deleteOne: { filter } } |
| Use | Targeted deletions |
6. Performing deleteMany in Bulk
| Aspect | Detail |
|---|---|
| Form | { deleteMany: { filter } } |
| Caution | Empty filter deletes all |
7. Performing replaceOne in Bulk
| Field | Description |
|---|---|
| filter | Selector |
| replacement | Whole document (no operators) |
| upsert | Bool |
8. Using Ordered Bulk Operations
| Aspect | Detail |
|---|---|
| Default | ordered: true |
| On error | Stops processing remaining ops |
| Use case | Op B depends on op A |
9. Using Unordered Bulk Operations
| Aspect | Detail |
|---|---|
| Setting | { ordered: false } |
| On error | Continues; collects all errors |
| Parallelism | Server may execute concurrently |
10. Handling Bulk Write Errors
| Property | Meaning |
|---|---|
| err.writeErrors | Per-op error array |
| err.writeConcernErrors | WC failures |
| err.result | Partial BulkWriteResult |
| err.code | Top-level error code |
try { await coll.bulkWrite(ops, { ordered: false }); }
catch (e) { for (const we of e.writeErrors) console.error(we.index, we.code, we.errmsg); }
11. Optimizing Bulk Performance
| Tip | Effect |
|---|---|
| Unordered | Server parallelism |
| Batch size 500-1000 | Sweet spot for round-trip vs memory |
| Avoid mixing ops | Server groups consecutive same-type ops |
| Hint | Force optimal index on each filter |
| Write concern | w:1 faster than w:"majority" |
12. Using Bulk Operations with Sessions
| Aspect | Detail |
|---|---|
| Within transaction | All ops atomic; bulkWrite supported |
| Causal consistency | Use session for read-your-writes |
| Restriction | Cannot create collection inside txn (4.4+ relaxes some) |