Working with Bulk Operations

1. Using bulkWrite() Method

AspectDetail
Signaturecoll.bulkWrite(operations, options)
OperationsArray of {insertOne|updateOne|updateMany|replaceOne|deleteOne|deleteMany}
ReturnsBulkWriteResult: counts + upsertedIds + insertedIds
Server batchDriver splits into batches ≤ 100k ops / 48MB

2. Performing insertOne in Bulk

FormResult
{ insertOne: { document: {...} } }One insert per op
Auto _idGenerated if missing

3. Performing updateOne in Bulk

FieldDescription
filterSelection
updateOperators or pipeline
upsertOptional bool
collationOptional
arrayFiltersOptional
hintForce index

4. Performing updateMany in Bulk

AspectDetail
Form{ updateMany: { filter, update } }
AtomicityPer document
RetryableNo

5. Performing deleteOne in Bulk

AspectDetail
Form{ deleteOne: { filter } }
UseTargeted deletions

6. Performing deleteMany in Bulk

AspectDetail
Form{ deleteMany: { filter } }
CautionEmpty filter deletes all

7. Performing replaceOne in Bulk

FieldDescription
filterSelector
replacementWhole document (no operators)
upsertBool

8. Using Ordered Bulk Operations

AspectDetail
Defaultordered: true
On errorStops processing remaining ops
Use caseOp B depends on op A

9. Using Unordered Bulk Operations

AspectDetail
Setting{ ordered: false }
On errorContinues; collects all errors
ParallelismServer may execute concurrently

10. Handling Bulk Write Errors

PropertyMeaning
err.writeErrorsPer-op error array
err.writeConcernErrorsWC failures
err.resultPartial BulkWriteResult
err.codeTop-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

TipEffect
UnorderedServer parallelism
Batch size 500-1000Sweet spot for round-trip vs memory
Avoid mixing opsServer groups consecutive same-type ops
HintForce optimal index on each filter
Write concernw:1 faster than w:"majority"

12. Using Bulk Operations with Sessions

AspectDetail
Within transactionAll ops atomic; bulkWrite supported
Causal consistencyUse session for read-your-writes
RestrictionCannot create collection inside txn (4.4+ relaxes some)