findOne() का उपयोग
findOne पहला matching document खुद return करता है, या कुछ भी match न करने पर null।
In this page:
Syntax
db.collection_name.findOne(filter)
db.collection_name.findOne(filter, projection)
findOne()
find के उलट, findOne एक cursor की बजाय एक single document object return करता है। बिना filter के यह natural order में पहला document return करता है। जब कोई match न हो यह null return करता है, जिसे आपको code में handle करना चाहिए।
Note:
जब आप ज़्यादा से ज़्यादा एक result expect करें findOne इस्तेमाल करें, जैसे _id से lookup।
उदाहरण: findOne()
test> db.users.insertMany([{ _id: 1, name: "Ada", age: 36 }, { _id: 2, name: "Bob", age: 25 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.users.findOne({ name: "Bob" })
{ _id: 2, name: 'Bob', age: 25 }
test> db.users.findOne({ name: "Zed" })
null
test> db.users.findOne({ age: { $gt: 30 } }, { name: 1, _id: 0 })
{ name: 'Ada' }
⚠️ 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. #}
आम गलतियां
- एक array की उम्मीद करना
- null handle न करना
- पहले document के लिए natural order पर depend करना
चैप्टर सारांश
- findOne एक document return करता है
- कुछ भी match न होने पर null
- _id से lookups के लिए useful
- एक deterministic pick के लिए sort add करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: