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.

CategoryWrite
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.findOneAndUpdate(<filter>, <update>, { returnDocument: 'after', upsert: <bool> })

⚙️ Parameters

filterPredicate matching the document to update.
updateObject of update operators, e.g. {$inc: {count: 1}}.
returnDocumentOptional. 'before' returns the pre-update document, 'after' the post-update one; default 'before'.
upsertOptional. 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏