πŸƒDBQuestpractice MongoDB queries
0 / 110

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

  1. Return every document in the restaurants collection. easy restaurants
  2. Return only the name, borough and cuisine fields for every restaurant. Keep _id. easy restaurants
  3. Return name, borough and cuisine for every restaurant, but drop _id. easy restaurants
  4. Return each restaurant's name and its address.zipcode only – no _id. easy restaurants
  5. Return every field of every restaurant except grades and address. easy restaurants
  6. Return a single restaurant located in the borough Bronx (not an array – one document). easy restaurants
  7. How many restaurants have price equal to 1? Return the number. easy restaurants
  8. List the distinct borough values present in the collection. easy restaurants
  9. 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 writeYou 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?

Set it to 0 in the second argument of find(): 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