replaceOne() - Complete document replacement
Syntax
Parameters
filter (Object, required)
Filter criteria to match documents to replace.
replacement (Object, required)
Replacement document, cannot contain update operators (such as $set).
Important:
- ❌ Cannot use
$set,$incand other operators - ✅ Provide complete new document objects directly
- The
_idfield will be automatically retained
options (Object, optional)
Return value
Return Promise<ReplaceResult>:
Key differences from updateOne
Behavior comparison example
Example
Basic replacement
Configuration management scenario
Use upsert
Preserve _id replacement
Custom _id replacement
Replace with empty document (clear all fields)
Nested object replacement
Common scenarios
Scenario 1: Configuration file management
Scenario 2: Document version management
Scenario 3: Complete state machine switching
Scenario 4: Clean and rebuild the document
Error handling
Common mistakes
Error 1: Using update operator
Mistake 2: Not realizing fields will be deleted
Performance recommendations
1. Filter using index fields
2. Pay attention to performance when using it with findOne
Caching behavior
replaceOne does not clear query caches by default after a successful replacement. Use cache.invalidate or autoInvalidate: true when the write should clear cache:
When to use replaceOne
✅ Suitable for scenarios where replaceOne is used
- Configuration Management - complete replacement of configuration objects
- Documentation Version - Replaced with new version
- State Machine - Complete state switching
- Data Cleaning - Delete old fields and rebuild
❌ Scenarios where replaceOne is not suitable
- Partial Update - Use
updateOneinstead - Count Up -
$incusingupdateOne - Array Operation -
$push/$pullusingupdateOne - Keep unmodified fields - use
updateOne
Decision tree
Best Practices
1. Clarify the document structure
2. Use TypeScript/JSDoc to define types
3. Verify the replacement result
Related methods
updateOne()- Partial update of a single documentfindOneAndReplace()- find and replace atomicallyinsertOne()- Insert a single document