findOneAndUpdate()
findOneAndUpdate updates a document and returns it in a single atomic step.
In this page:
Syntax
db.collection_name.findOneAndUpdate(
filter,
{ $set: { field: value } },
{ returnDocument: "after" }
)
findOneAndUpdate()
By default it returns the document as it was before the update; set returnDocument to "after" to get the new version. It is the tool for queue-like patterns and counters where you need the value that resulted.
Sort decides which document is chosen when several match.
Note:
Use returnDocument: "after" to get the updated document.
Example: findOneAndUpdate()
test> db.counters.insertOne({ _id: "orders", seq: 100 })
{ acknowledged: true, insertedId: 'orders' }
test> db.counters.findOneAndUpdate({ _id: "orders" }, { $inc: { seq: 1 } })
{ _id: 'orders', seq: 100 }
test> db.counters.findOneAndUpdate({ _id: "orders" }, { $inc: { seq: 1 } }, { returnDocument: "after" })
{ _id: 'orders', seq: 102 }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting the updated document by default
- Using it where updateOne would do
- Forgetting sort with multiple matches
Chapter Summary
- Updates and returns one document
- Returns the old document by default
- returnDocument after returns the new one
- Atomic per document
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: