Skip to content
LESSON 34 / 50Beginneraggregation

Document Reshaping: $project vs $addFields vs $set

Compare document transformation stages: $project selects and renames explicit fields, while $addFields and $set append computed values while preserving all existing document attributes.

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

1. Formal Definition & Architecture Intent

Document reshaping stages transform document structure. $project specifies an explicit whitelist or blacklist of fields, discarding unmentioned fields. $addFields (and its alias $set) appends new computed fields or overwrites existing ones while automatically preserving all other document fields without verbose whitelisting.

2. Explain Like I'm 5 (Mental Model)

$project is like packing a suitcase where you must list every single shirt, sock, and shoe you want to bring. $addFields is like grabbing your existing packed suitcase and just slipping a book into the side pocket.

3. Real-World Architecture Example

Calculating an order total with sales tax without losing the other 20 order fields.

Sample BSON Documents:
Collection: db.orders
{
  "_id": "o1",
  "subtotal": 100,
  "taxRate": 0.08,
  "customer": "Alice",
  "notes": "Urgent"
}

$addFields appends totalAmount without requiring you to manually re-list customer, notes, etc.

4. MQL Implementation Steps

Step 1: Append calculated field using $set or $addFields
db.orders.aggregate([
  {
    $set: {
      totalAmount: { $multiply: ["$subtotal", { $add: [1, "$taxRate"] }] },
      processedDate: new Date()
    }
  }
]);
$set preserves all original fields automatically.
Step 2: Strict projection using $project
db.orders.aggregate([
  {
    $project: {
      _id: 0,
      orderNumber: "$_id",
      subtotal: 1
    }
  }
]);
$project discards all unmentioned fields.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
$projectExplicit whitelist or blacklist. Only specified fields survive into the next stage.
$addFields / $setNon-destructive: keeps all existing document attributes and appends or overwrites target fields.

6. Deep Dive: Conditional Expressions with $cond and $switch

Both $project and $set support powerful inline ternary logic. The $cond operator evaluates boolean expressions: { $cond: [ { $gte: ["$score", 90] }, "A", "B" ] }. For multi-branch logic, $switch replaces deeply nested ternary clauses with clean case statements.

// Multi-case grading with $switch:
db.students.aggregate([
  {
    $set: {
      grade: {
        $switch: {
          branches: [
            { case: { $gte: ["$score", 90] }, then: "A" },
            { case: { $gte: ["$score", 80] }, then: "B" }
          ],
          default: "C"
        }
      }
    }
  }
]);
Production Warning: Do not use $project if you only want to add 1 field to a document with 50 fields.

7. Architectural Trade-offs

Advantages
  • •$set and $addFields eliminate massive boilerplate when appending computed attributes
  • •$project protects privacy by pruning sensitive fields (e.g. passwordHash, ssn) before client delivery
  • •Supports mathematical, string, array, and date transformation operators
Disadvantages & Gotchas
  • •Excessive field creation in long pipelines increases memory size per document
  • •Overwriting fields with different BSON types can break downstream stage assumptions

8. Technical Interview Questions

Q1: When should you choose $addFields (or $set) over $project in an aggregation pipeline?

Use $addFields (or $set) when you want to append new computed fields or update existing values while preserving all other fields in the document. Use $project when you need to construct a strict whitelist of returned fields, rename fields, or explicitly suppress fields (like _id) to prune payload size.

9. Staff-Level Ready Answer

"$project constructs an explicit whitelist/blacklist of fields, dropping unmentioned fields. $addFields (aliased as $set in MongoDB 4.2+) non-destructively adds or updates specific fields while keeping all other existing attributes intact."

10. Quick Knowledge Check

Which aggregation stage allows you to append a new computed field to a document without discarding its other existing fields?