MongoDB Aggregation $project
MongoDB Aggregation $project 🎯
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/exclude | Advanced transformations |
| No expressions | Supports expressions |
| Used in find | Used in aggregation |
Common Mistakes ⚠️
Mixing
1and0incorrectlyForgetting
$before field namesExpecting original fields after
$group
Best Practices 👍
Use
$projectto reduce data sizePlace it after
$groupfor clean outputAvoid unnecessary fields early
