MongoDB find() and projection
find, findOne, picking fields, counting, distinct. Β· 9 practice questions Β· Cheat sheet β
Every read in MongoDB starts with find(). The first argument is a filter document that says which documents you want; the second is a projection that says which fields to bring back. Leave the filter empty and you get the whole collection; leave the projection out and you get whole documents. findOne() returns the first match instead of a cursor, countDocuments() counts without fetching, and distinct() lists the unique values of one field.
Projection is where most people trip. You either include fields ({ name: 1, borough: 1 }) or exclude them ({ grades: 0 }), never both in one projection, with _id as the single exception: it comes back unless you switch it off with _id: 0. The questions here are MongoDB find query examples that build these habits before operators and pipelines arrive.
MongoDB find() practice questions
- Return every document in the
restaurantscollection. easy restaurants - Return only the
name,boroughandcuisinefields for every restaurant. Keep_id. easy restaurants - Return
name,boroughandcuisinefor every restaurant, but drop_id. easy restaurants - Return each restaurant's
nameand itsaddress.zipcodeonly β no_id. easy restaurants - Return every field of every restaurant except
gradesandaddress. easy restaurants - Return a single restaurant located in the borough
Bronx(not an array β one document). easy restaurants - How many restaurants have
priceequal to 1? Return the number. easy restaurants - List the distinct
boroughvalues present in the collection. easy restaurants - List the distinct cuisines served in
Queens. medium restaurants
Each question is answered in a live mongo-shell editor on this page; the result is checked against a reference solution.
find() and projection cheat sheet
The shape of a read
db.<collection>.find(<filter>, <projection>)
- filter β which documents.
{}or omitted means all of them. - projection β which fields come back.
Projection rules
| You write | You get |
|---|---|
{ name: 1, borough: 1 } | name, borough and _id |
{ name: 1, _id: 0 } | name only |
{ grades: 0 } | everything except grades |
{ "address.street": 1, _id: 0 } | just the nested street |
You cannot mix 1s and 0s in one projection β the only exception is turning
_id off while turning other fields on.
Other reads
db.restaurants.findOne({ borough: "Bronx" }) // one doc, not an array
db.restaurants.countDocuments({ price: 1 }) // a number
db.restaurants.distinct("cuisine") // array of unique values
Gotchas
find()returns a cursor, not an array. In the shell it prints for you.- Dotted paths need quotes:
{ "address.zipcode": "10011" }.
Common questions
How do I exclude a field in a MongoDB projection?
db.restaurants.find({}, { grades: 0 }). You can exclude several fields, but you cannot mix inclusion and exclusion in one projection. The exception is _id: { name: 1, _id: 0 } is allowed.What's the difference between find() and findOne()?
find() returns a cursor over every matching document; findOne() returns the first match as a plain document, or null when nothing matches. Use findOne when you expect exactly one result, such as a lookup by a unique key.How do I count documents without fetching them?
countDocuments(filter) returns the number of matches without transferring the documents. estimatedDocumentCount() is faster for a whole collection because it reads metadata, but it ignores filters. distinct("field") lists unique values rather than counting.Continue:Comparison Operators β
MongoDB topics:Comparison OperatorsLogical OperatorsElement & TypePattern MatchingSort, Limit & SkipArray QueriesEmbedded DocumentsAggregation BasicsGrouping & Accumulators$unwind & Array PipelinesJoins & Advanced StagesFull cheat sheet