Projection & Sorting

Once you've filtered your data, Projection and Sorting allow you to control exactly what data is returned and in what order.

1. Projection

Projection is more efficient than fetching full documents when you only need a few fields. It reduces network traffic and CPU usage.

// Include only name and email (1 for include, 0 for exclude)
db.users.find({}, { name: 1, email: 1 })

// Exclude sensitive fields like password
db.users.find({}, { password: 0 })

// Note: You cannot mix include and exclude (except for _id)
// INCORRECT: { name: 1, email: 0 } 
// CORRECT: { _id: 0, name: 1 }

2. Sorting

The `sort()` method specifies the order in which the query returns matching documents.

  • 1: Ascending order (A to Z, 0 to 9).
  • -1: Descending order (Z to A, 9 to 0).
// Sort by age ascending
db.users.find().sort({ age: 1 })

// Sort by age descending
db.users.find().sort({ age: -1 })

// Sort by multiple fields (Sort by status, then by age)
db.users.find().sort({ status: 1, age: -1 })
Pro Tip: For large datasets, always ensure your sort fields are indexed to avoid slow "In-Memory Sort" operations.