MongoDB Aggregation $project

MongoDB Aggregation $project 🎯

In MongoDB, the $project stage is used in the Aggregation Pipeline to control the shape of documents—you can include, exclude, rename, or compute fields.

What does $project do?

  • Select which fields to show or hide

  • Rename fields

  • Create new computed fields

  • Transform document structure

  • Similar to SELECT columns in SQL (but more powerful)


Basic Syntax


📌 1 = include field
📌 0 = exclude field


1️⃣ Include Specific Fields

Example: Show only name and course



2️⃣ Exclude Fields

Example: Hide _id


📌 By default, _id is included unless excluded.


3️⃣ Rename Fields



4️⃣ Create Computed Fields

Example: Calculate next year’s age



5️⃣ Use Expressions in $project

Conditional Field ($cond)



6️⃣ $project with Arrays

Example: Array length



7️⃣ $project After $group


📌 Used to clean and rename output


SQL vs MongoDB $project

SQL


MongoDB



$project vs Projection in find()

find() projection$project
Simple include/excludeAdvanced transformations
No expressionsSupports expressions
Used in findUsed in aggregation

Common Mistakes ⚠️

  • Mixing 1 and 0 incorrectly

  • Forgetting $ before field names

  • Expecting original fields after $group


Best Practices 👍

  • Use $project to reduce data size

  • Place it after $group for clean output

  • Avoid unnecessary fields early


Quick Recap 🧠


 

You may also like...