MongoDB Aggregation $addFields
MongoDB Aggregation $addFields ➕🧩
What does $addFields do?
-
Adds new computed fields
-
Modifies existing fields
-
Keeps all original fields
-
Similar to adding calculated columns in SQL
📌 Think of $addFields as $project without hiding fields
Basic Syntax
1️⃣ Add a Simple New Field
Example: Add status field
2️⃣ Add Computed Field (Calculation)
Example: Calculate next year’s age
3️⃣ Modify an Existing Field
Example: Increase marks by 5
📌 Original marks field is updated in output only (no DB change).
4️⃣ Conditional Field using $cond
Example: Adult or Minor
5️⃣ $addFields with Arrays
Example: Count number of skills
6️⃣ $addFields with Dates
Example: Add current date
7️⃣ $addFields After $group
Example: Add readable label
📌 Often used to clean grouped output
$addFields vs $project
$addFields |
$project |
|---|---|
| Adds fields | Selects/removes fields |
| Keeps all fields | Can remove fields |
| Safer for enrichment | Used for shaping output |
Example equivalence:
SQL Comparison
SQL
MongoDB
Best Practices 👍
-
Use
$addFieldswhen you don’t want to lose fields -
Combine with
$matchfor efficiency -
Prefer
$projectonly when you need field control
Common Mistakes ❌
-
Expecting
$addFieldsto update database (it doesn’t) -
Forgetting
$before field names -
Using
$projectwhen$addFieldsis simpler
