findOneAndReplace() - Atomic find and replace
Syntax
Parameters
filter (Object, required)
Filter criteria.
replacement (Object, required)
Replacement document, cannot contain update operators.
options (Object, optional)
Return value
Default returns Document Object or null (not found).
If includeResultMetadata: true, return:
⚠️ IMPORTANT NOTE - MongoDB Driver 6.x Compatibility
monSQLize uses MongoDB Node.js driver 6.x, which makes important changes to the return value format of
findOneAndReplace:Driver 6.x (current version):
- By default, the document object is returned directly
- Requires explicit setting of
includeResultMetadata: trueto return complete metadataDriver 5.x and earlier:
- Return complete metadata
{ value, ok, lastErrorObject }by default✅ monSQLize processing:
- This difference has been automatically handled internally, users do not need to care about the driver version
- API behavior remains consistent and backward compatible
- For the current verification entry, see MongoDB Driver Version Compatibility Guide and findOneAnd* Return Value Unified Description
Core Features
Atomic guarantee
Differences from findOneAndUpdate
Common scenarios
Scenario 1: Configuring atomic replacement
Scenario 2: Version Management
Scenario 3: State machine transition
Scenario 4: Distributed lock configuration
Example
Basic usage
Return the replaced document
Use sorting
Use projection
Use upsert
Error handling
Common mistakes
Error 1: Using update operator
Mistake 2: Forgot fields will be deleted
Performance recommendations
1. Use index
2. Use projection to reduce data transmission
Concurrency safety
Security Example
Best Practices
1. Save historical versions
2. Use version number
3. Verification results
When to use
✅ Suitable for use findOneAndReplace
- Old value required - You need to view the original document before replacing
- Atomic Operations - Prevent race conditions
- Configuration Management - complete replacement configuration
- State Machine - complete state switching
❌ Not suitable for use with findOneAndReplace
- Partial Update - Use
findOneAndUpdate - Old value not required - use
replaceOne - RESERVED FIELD - Use
findOneAndUpdate
Related methods
findOneAndUpdate()- atomically find and partially updatereplaceOne()- complete replacement of a single documentfindOne()- Find a single document