deleteBatch - delete documents in batches
API parameter description
Method signature
Detailed explanation of parameters
First parameter: filter (required)
- Type:
object - Description: Deletion condition, same as
deleteMany
Second parameter: options (optional)
Return value
Progress callback parameters
Usage example
1. Basic usage - clear expired logs
2. With progress monitoring - cleaning large amounts of data
Example output:
3. No pre-count - avoid performance overhead
4. Error handling - stop strategy (default)
5. Error handling - skip strategy
6. Error handling - retry strategy (recommended)
7. Error handling - collect strategy
8. Complex query conditions
9. Use comment to track operations
Performance optimization suggestions
1. Batch size selection
2. Whether to count in advance
3. Index optimization
4. Wrong strategy selection
FAQ
Q1: What is the difference between deleteBatch and deleteMany?
Suggestions:
- Data volume < 10000 items → use
deleteMany - Data volume ≥ 10000 → use
deleteBatch
Q2: Will deleteBatch cause data inconsistency?
Answer: deleteBatch processes matching _id values through a cursor and deletes them in batches. It does not create a MongoDB transaction or guarantee snapshot isolation by itself. If you need a transactional snapshot, run it inside an explicit transaction and pass the transaction session.
Q3: How do I know which documents have been deleted?
Q4: Will deleteBatch trigger slow query logs?
Answer: Yes. If the delete operation exceeds the threshold (default 500ms), slow query logs will be recorded.
Q5: Can deleteBatch be used in a transaction?
Answer: Yes, but please note: