MongoDB find() and findOne() Tutorial: Query & Projection
Learn MongoDB's find() and findOne() methods, how to filter documents with a query object, query nested fields, and select specific fields with projection.
find() and findOne()
MongoDB gives you two core methods for reading documents out of a collection: find() and findOne().
find()
Returns all documents that match a query object. Leave the query empty to return every document in the collection.
db.collection.find()
db.employees.find()
// returns every document in the employees collection
findOne()
Returns only the first matching document. Leave the query empty and it returns the first document it finds.
db.collection.findOne()
Query Documents
Pass a condition object as the first argument to filter results.
db.employees.findOne({ city: "Mumbai" })
// returns the first document where city is Mumbai
db.employees.find({ city: "Mumbai" })
// returns every document where city is Mumbai
Querying Nested (Embedded) Fields
Use dot notation, wrapped in quotes, to reach into an embedded document.
db.employees.find({ 'reportinmgr.mgrid': 105 })
Projection
Both find() and findOne() accept a second argument — the projection — that controls which fields come back in the result.
db.collection.find({}, { field: 1 })
db.employees.find({}, { name: 1 })
// { _id: ObjectId(...), name: 'Rahul Gupta' }
Notice _id is included by default even though it wasn't listed — MongoDB always returns _id unless you explicitly exclude it.
db.employees.find({}, { name: 1, email: 1 })
// returns _id, name and email for every document
db.employees.find({}, { _id: 0, name: 1 })
// { name: 'Rahul Gupta' }
- Use
1to include a field. - Use
0to exclude a field. - You can also exclude just one field and get everything else, e.g.
{ reportinmgr: 0 }.
Common Errors & Troubleshooting
- A nested-field query returns nothing — dot-notation paths like
'reportinmgr.mgrid'must be a quoted string, notreportinmgr.mgridwritten bare — unquoted dots aren't valid JavaScript object key syntax. - Projection returns
_ideven though you only listed other fields —_idis included by default in every projection; you must exclude it explicitly with{ _id: 0, ... }if you don't want it. - Mixing inclusion and exclusion in one projection —
{ name: 1, email: 0 }throws an error. You can't mix1s and0s in the same projection object, except for the special case of excluding just_idalongside inclusions.
Key Takeaways
find()returns a cursor over all matches;findOne()returns a single document.- Query nested fields with dot notation in quotes:
"parent.child". - Projection's second argument decides which fields are returned —
_idis included unless you set it to0.