Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Collections & Methods  ›  Lesson

Finding Documents

find() and relevant 14 minfind takes a filter document whose fields are combined with AND and returns a cursor that can be sorted, skipped and limited, while findOne returns the first match or null.

Finding Documents

"Show me classic books with plenty of copies, cheapest first." That sentence is a filter, a sort and maybe a limit. In MongoDB each part becomes one piece of a find call, and once you see the pieces, every read query looks the same.

The rule

A filter document chooses, the cursor shapes: sort, then skip, then limit.

The running collection, briefly:

_id title year price stock genres
1 Dune 1965 9.99 12 sci-fi, classic
2 Neuromancer 1984 8.5 0 sci-fi, cyberpunk
3 Emma 1815 4.25 7 classic, romance
4 The Hobbit 1937 7.99 3 fantasy, classic, adventure
5 Circe 2018 12 5 fantasy, myth
db.books.find({ genres: "classic", stock: { $gt: 5 } })   // Dune, Emma
db.books.findOne({ title: "Circe" })                      // the Circe document
db.books.find({}, { title: 1, _id: 0 })                   // every title, nothing else
  • The filter is a document. Several fields in it are combined with AND. {} matches everything.
  • find returns a cursor, a pointer that fetches results in batches. mongosh prints the first 20; type it for more.
  • findOne returns one document, or null if nothing matches.
  • The optional second argument is a projection that picks fields to return; a later lesson covers it.
  • Cursor methods: .sort({ field: 1 }) ascending or -1 descending, .skip(n), .limit(n).

However you chain them, MongoDB applies sort, then skip, then limit.

The shortcut

Split the question into which (filter), in what order (sort) and how many (skip, limit).

Second and third oldest booksStep 1 of 4
  1. Which

    All books: filter {}.

The trap: writing .limit(2).sort({ price: -1 }) and expecting "any two books, then sorted". MongoDB still sorts the whole result first, then takes two.

Drills

Answer fast — trust the rule.

quick drill

What does db.books.find({ genres: "classic", stock: { $gt: 5 } }) return?

quick drill

What does findOne return when nothing matches?

quick drill

What does db.books.find().sort({ price: -1 }).limit(2) return?

quick drill

What does db.books.find().limit(1).sort({ year: 1 }) return?

Remember

  • A filter document chooses; the cursor shapes: sort, then skip, then limit.
  • Shortcut: which, in what order, how many.
  • Trap: fields in one filter are ANDed, and chain order never changes sort-before-limit.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe shop's front page

The shop's front page shows the two most expensive books that are in stock. Write the mongosh query, say which books it returns from the books collection, and explain what each part of the query does.