Skip to the workspace
Pebellslearn by building
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.

mongodb / Finding Documents

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.