findOne()
findOne returns the first matching document itself, or null when nothing matches.
In this page:
Syntax
db.collection_name.findOne(filter)
db.collection_name.findOne(filter, projection)
findOne()
Unlike find, findOne returns a single document object rather than a cursor. With no filter it returns the first document in natural order. It returns null when there is no match, which you should handle in code.
Note:
Use findOne when you expect at most one result, such as lookup by _id.
Example: 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
- Expecting an array
- Not handling null
- Relying on natural order for the first document
Chapter Summary
- findOne returns one document
- null when nothing matches
- Useful for lookups by _id
- Add sort for a deterministic pick
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: