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. findreturns a cursor, a pointer that fetches results in batches. mongosh prints the first 20; typeitfor more.findOnereturns 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-1descending,.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).
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.
What does db.books.find({ genres: "classic", stock: { $gt: 5 } }) return?
What does findOne return when nothing matches?
What does db.books.find().sort({ price: -1 }).limit(2) return?
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.
