Mongodb Guide

$project Stage in MongoDB Aggregation Pipeline

1. Definition

The $project stage is used to reshape documents by selecting, including, excluding, or modifying fields in the output.

2. Simple Understanding

👉 It works like selecting columns in SQL
👉 You control what fields appear in the final result

3. When to Use

  • When you want specific fields only
  • When removing unnecessary data
  • When renaming fields
  • When transforming data structure

4. Where it is Used

  • Aggregation pipelines
  • API responses
  • Data transformation
  • Frontend data shaping

5. Why We Use It

  • Reduce data size
  • Improve performance
  • Customize output
  • Hide sensitive fields

6. How It Works

  • 1 → include field
  • 0 → exclude field
  • Can rename fields
  • Can create computed fields

7. Basic Syntax

db.collection.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      _id: 0
    }
  }
]);

8. Real Example

// Show only name and role
db.users.aggregate([
  {
    $project: {
      name: 1,
      role: 1,
      _id: 0
    }
  }
]);

// Rename field
db.users.aggregate([
  {
    $project: {
      username: "$name",
      _id: 0
    }
  }
]);

// Create computed field
db.products.aggregate([
  {
    $project: {
      name: 1,
      discountedPrice: { $multiply: ["$price", 0.9] }
    }
  }
]);

9. Explanation

  • $project controls output fields
  • 1 includes, 0 excludes fields
  • Can rename and transform data
  • Helps optimize response size

10. Advantages

  • Custom output structure
  • Reduces data transfer
  • Improves performance
  • Flexible transformations

11. Disadvantages

  • Complex transformations can be hard to read
  • Requires proper field handling

Interview Points

  • $project = SELECT in SQL
  • Controls output fields
  • 1 include, 0 exclude
  • Supports renaming and computed fields