findOneAndUpdate() (Update and Return a Document)
Last updated: 2026-10-09
findOneAndUpdate() (Update and Return a Document)
findOneAndUpdate() updates the first document matching a filter and returns the document itself — before or after the update, controlled by `returnDocument`: 'before' (default) or 'after', e.g. `db.users.findOneAndUpdate({ name: 'Alice' }, { $set: { age: 22 } }, { returnDocument: 'after' })`. Unlike updateOne(), which only returns counters, it reads the document back, suiting flows that need the fresh value immediately, such as counters or state-machine transitions.
| Category | Write |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.findOneAndUpdate(<filter>, <update>, { returnDocument: 'after', upsert: <bool> })
⚙️ Parameters
| filter | Predicate matching the document to update. |
|---|---|
| update | Object of update operators, e.g. {$inc: {count: 1}}. |
| returnDocument | Optional. 'before' returns the pre-update document, 'after' the post-update one; default 'before'. |
| upsert | Optional. Insert when nothing matches; default false. |
Returns:The document before (or after) the update; null if nothing matched and upsert is off.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// findOneAndUpdate: update Alice, return the new doc
const doc = db.users.findOneAndUpdate(
{ name: 'Alice' }, { $set: { age: 22 } },
{ returnDocument: 'after' }
)
doc
Output:
{
_id: ObjectId('64c8a1b20000000000000001'),
name: 'Alice',
age: 22
}
📌 Notes
- Returns the pre-update document by default; set returnDocument: 'after' for the new value
- Legacy drivers call this findAndModify with option new instead of returnDocument
- updateOne() returns counters; use this method when you need the document itself
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes findOneAndUpdate return the document before or after the update?
ABy default it returns the pre-update document; pass {returnDocument: 'after'} for the post-update one.
QWhat is the difference between findOneAndUpdate and updateOne?
AupdateOne() returns counters only; findOneAndUpdate() returns the document, handy when you need the old or new value.
QWhat does findOneAndUpdate return when nothing matches?
AIt returns null (with upsert off). With upsert on, a new document is inserted and returned.