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

findOneAndUpdate() का उपयोग

findOneAndUpdate एक single atomic step में एक document update करता है और इसे return करता है।

In this page:

  1. findOneAndUpdate()
Syntax
javascript
db.collection_name.findOneAndUpdate(
  filter,
  { $set: { field: value } },
  { returnDocument: "after" }
)

findOneAndUpdate()

Default से यह document को update से पहले जैसा था वैसे return करता है; नया version पाने के लिए returnDocument को "after" set करें। queue-like patterns और counters के लिए यह tool है जहाँ आपको resulting value चाहिए।

जब कई match करें Sort decide करता है कौन-सा document चुना जाए।

Note: updated document पाने के लिए returnDocument: "after" इस्तेमाल करें।

उदाहरण: 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. #}
आम गलतियां
  1. default से updated document की उम्मीद करना
  2. इसे वहाँ इस्तेमाल करना जहाँ updateOne काफी होता
  3. कई matches के साथ sort भूल जाना
चैप्टर सारांश
  • एक document update और return करता है
  • Default से old document return करता है
  • returnDocument after नया वाला return करता है
  • हर document के लिए Atomic है
🔒

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.