Lesson 10 +10 XP

Find Documents

Find Documents

Reading data is the "R" in CRUD. MongoDB gives you find() (all matches) and findOne() (the first match).

Get everything

db.posts.find()

Returns all documents in the collection. In mongosh, find() displays the first 20 documents - type it to keep going.

Get the first document

db.posts.findOne()

Returns only the first matching document.

Filter with a query object

Pass a query object to filter the results:

db.posts.find({ category: "News" })

Query operators

Filters can use operators like $gt (greater than):

db.posts.find({ likes: { $gt: 1 } })

Projection: choose which fields to return

The second argument to find() is a projection. Use 1 to include a field and 0 to exclude one:

// Include only title and date
db.posts.find({}, { title: 1, date: 1 })

// Exclude _id, include title and date
db.posts.find({}, { _id: 0, title: 1, date: 1 })

// Exclude category, keep everything else
db.posts.find({}, { category: 0 })

Projection rules

  • _id is always included unless you explicitly set _id: 0.
  • You cannot mix 0 and 1 in the same projection, except for _id.
  • This line is an error: db.posts.find({}, { title: 1, date: 0 }).

find() returns a cursor

Technically find() returns a cursor, not the documents directly. You can chain methods like cursor.sort(), cursor.limit(), and cursor.toArray().

TL;DR

  • find() gets all matches; findOne() gets the first.
  • Filters use query objects and operators.
  • Projection picks which fields to include (1) or exclude (0).