← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 6 of 7

findOneAndUpdate()

findOneAndUpdate updates a document and returns it in a single atomic step.

In this page:

  1. findOneAndUpdate()
Syntax
javascript
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()

bash
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting the updated document by default
  2. Using it where updateOne would do
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.