Lesson 5 of 18

Querying Documents

Find Documents

Use find() to query documents. Pass a filter object to match specific criteria.

Example
// Find all documents
db.users.find()

// Find with filter
db.users.find({ name: "Alice" })

// Find one document
db.users.findOne({ email: "alice@example.com" })

// Multiple conditions (AND)
db.products.find({ category: "Electronics", price: { $lt: 500 } })

// Projection — select specific fields
db.users.find({}, { name: 1, email: 1, _id: 0 })
// Returns only name and email, hides _id

// Pretty print
db.users.find().pretty()

Sorting, Limiting, and Skipping

Chain methods to sort results, limit the number returned, and skip documents for pagination.

Example
// Sort ascending (1) or descending (-1)
db.products.find().sort({ price: 1 })   // cheapest first
db.products.find().sort({ price: -1 })  // most expensive first

// Limit results
db.products.find().limit(5)

// Skip for pagination
db.products.find().skip(10).limit(5)  // page 3 (5 per page)

// Count documents
db.products.countDocuments({ category: "Electronics" })

// Chain everything
db.products.find({ category: "Electronics" })
  .sort({ price: -1 })
  .limit(3)