findOneAndUpdate() - Atomic find and update
Syntax
Parameters
filter (Object, required)
Filter criteria.
update (Object, required)
For update operations, the update operator must be used.
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
findOneAndUpdate: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
returnDocument option
Common scenarios
Scenario 1: Distributed counter
Scenario 2: Optimistic locking (version control)
Scenario 3: Task Queue
Scenario 4: Distributed lock
Scenario 5: User’s last activity time
Example
Basic usage
Use sorting
Use projection
Use upsert (insert if it does not exist, update if it exists) ⭐
Upsert detailed description
Combination of upsert = update + insert:
- ✅ EXISTS: Perform update operation
- ✅ Does not exist: Insert new document
Usage Scenario:
⚠️Upsert Notes:
Get complete metadata
Performance optimization
1. Use index
2. Use projection to reduce data transmission
3. Optimize queries with sort and hint
Error handling
Comparison with other methods
Concurrency safety
Security Example
Best Practices
1. Reasonable choice of returnDocument
2. Use version numbers to avoid conflicts
3. Use projection to optimize performance
Related methods
findOneAndReplace()- find and replace atomicallyupdateOne()- Update a single documentfindOne()- Find a single document