MongoDB Aggregation $addFields

MongoDB Tutorial

MongoDB Aggregation $addFields ➕🧩

In MongoDB, the $addFields stage is used in an Aggregation Pipeline to add new fields or modify existing fields in documents without removing any existing data.

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 $addFields when you don’t want to lose fields

  • Combine with $match for efficiency

  • Prefer $project only when you need field control


Common Mistakes ❌

  • Expecting $addFields to update database (it doesn’t)

  • Forgetting $ before field names

  • Using $project when $addFields is simpler


Quick Recap 🧠


 

You may also like...