findOneAndUpdate()

Reference type:Cheat sheetFormat:Syntax + example + use case

Reference group: Collection CRUD methods

What it does

Atomically updates one document and can return its before/after state.

Syntax

db.collection.findOneAndUpdate(filter, update, options)

Use case

Reserve inventory and return the resulting document.

findOneAndUpdate(): practical example
db.inventory.findOneAndUpdate({ sku: "KB-1", stock: { $gt: 0 } }, { $inc: { stock: -1 } }, { returnDocument: "after" })
💡 Explanation Atomically updates one document and can return its before/after state. When to use it Reserve inventory and return the resulting document.
Key Takeaways
  • Atomically updates one document and can return its before/after state.
  • Typical use: Reserve inventory and return the resulting document.