Chapter 15: MongoDB Aggregation $project

1. What does $project really do? (Teacher explanation — no jargon first)

$project lets you:

  1. Decide which fields you want to keep in the output documents
  2. Decide which fields you want to remove
  3. Rename fields
  4. Create brand new computed / derived fields using expressions
  5. Reshape nested documents
  6. Include / exclude the _id field (very important!)

In simple words:

After previous stages have done filtering, grouping, sorting… $project is the final makeup artist — it decides what the output document should look like before it reaches your application or the next stage.

2. Two Main Styles of $project (Very Important to Understand)

There are two completely different ways people write $project — and mixing them up causes 90% of beginner confusion.

Style Syntax looks like What it means When to use it
Inclusion / Exclusion { fieldA: 1, fieldB: 1, _id: 0 } 1 = keep this field, 0 = remove this field Quick clean-up of unwanted fields
Reshaping / Computed { newName: “$oldName”, calc: { $add: […] } } Expressions, new fields, renaming Almost every real-world pipeline

Rule teacher screams three times:

You cannot mix inclusion/exclusion style (0 and 1) with expression style in the same $project stage (except for _id).

Wrong (MongoDB will throw error in most versions):

JavaScript

Correct ways:

  • Use only 0/1 style → simple keep/remove
  • Use expression style → create/rename/compute (most powerful & common)

3. Hands-on Examples — Using Our Movie Collection

JavaScript

Example 1: Inclusion / Exclusion style (simple cleanup)

JavaScript

→ Output documents contain only: title, rating, year

Example 2: Expression style — Rename + create new fields

JavaScript

Example 3: Real analytics — After $group + computed fields

JavaScript

Example 4: Nested reshaping + conditional logic

JavaScript

4. Quick Reference Table – $project Cheat Sheet

Goal Style used Typical syntax snippet Notes / Tip
Remove _id & few unwanted fields Inclusion { title: 1, rating: 1, _id: 0, comments: 0 } Fast & simple
Rename fields Expression { movieName: “$title”, relYear: “$year” } Very common
Create boolean flag Expression { isHighRated: { $gte: [“$rating”, 8] } } Great for UI filters
Round numbers Expression { avgRating: { $round: [“$avgRating”, 1] } } Clean presentation
Conditional new field Expression { $cond: { if: …, then: …, else: … } } or $switch Replaces CASE WHEN in SQL
Slice / take subset of array Expression { recentComments: { $slice: [“$comments”, -3] } } Last 3 elements (-3)
Concatenate strings Expression { fullInfo: { $concat: [“$title”, ” (“, { $toString: “$year” }, “)” ] } } Display friendly

5. Mini Exercise – Try Right Now!

  1. Show only title, rating, year — hide everything else (inclusion style)
  2. Create a pipeline that shows:
    • movieTitle
    • ratingStars (multiply rating by 1 → same, just rename)
    • isSuperhit (true if rating ≥ 8.3)
    • boxOfficeMessage = “₹” + revenue + ” Cr” (use $concat)
  3. After grouping by country — project country name, total revenue, avg rating rounded to 1 decimal

Understood beta? $project is like the final filter on what your boss / user actually sees — spend time mastering expressions here and your reports become clean, beautiful, and useful.

Next class — what do you want?

  • $addFields vs $project (when to use which)
  • $project inside $lookup (joined data reshaping)
  • String, date, math operators inside $project
  • Or continue building a full “Movie Insights Dashboard” pipeline?

Tell me — class is still full of energy! 🚀❤️

Any confusion with $project? Ask anything — we’ll fix it together 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *