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.