updateMany() - Update documents in batches
Syntax
Parameters
filter (Object, required)
Filter criteria to match the documents to be updated.
update (Object, required)
For update operations, the update operator must be used.
options (Object, optional)
Return value
Return Promise<UpdateResult>:
Upsert semantics
updateMany(filter, update, { upsert: true }) follows MongoDB's native semantics:
- If one or more documents match
filter, all matching documents are updated. - If no documents match
filter, MongoDB inserts one new document derived from the equality parts offilterand theupdatedocument. - It is not a per-input bulk upsert. For multiple independent keys, run separate
upsertOne()calls or use nativebulkWriteupdateOnemodels withupsert: true.
Example
Batch update status
Batch increment
Conditional batch update
Add fields in batches
Delete fields in batches
Use array filter
Complex updates with multiple conditions
Batch update nested fields
Performance optimization
1. Use index optimization filtering
2. Process large-scale updates in batches
3. Performance test example
Differences from updateOne
Common scenarios
Scenario 1: Batch activation of users
Scenario 2: Mark expired data in batches
Scenario 3: Bulk price adjustment
Scenario 4: Batch data migration
Error handling
Caching behavior
updateMany does not clear query caches by default after a successful modification. Use cache.invalidate or autoInvalidate: true when the write should clear cache:
Note: Explicit invalidation runs only when the write path decides the operation changed data.
Slow query log
If the batch update operation takes a long time, slow query logs will be automatically recorded:
Best Practices
1. Verify update results
2. Add operation comments
3. Use transaction processing key batch update
4. Monitor update progress
Related methods
updateOne()- Update a single documentreplaceOne()- complete replacement of a single documentinsertMany()- Batch insert documents