← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 2 of 7

findOne()

findOne returns the first matching document itself, or null when nothing matches.

In this page:

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

bash
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. #}
Common Mistakes
  1. Expecting an array
  2. Not handling null
  3. 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:

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.