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.
Aggregation Pipeline Multi-Stage Stream Stepper
Filter completed orders, aggregate total revenue by payment method, and sort highest first.
The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.
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.
{
"_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
db.orders.aggregate([
{
$set: {
totalAmount: { $multiply: ["$subtotal", { $add: [1, "$taxRate"] }] },
processedDate: new Date()
}
}
]);db.orders.aggregate([
{
$project: {
_id: 0,
orderNumber: "$_id",
subtotal: 1
}
}
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| $project | Explicit whitelist or blacklist. Only specified fields survive into the next stage. |
| $addFields / $set | Non-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"
}
}
}
}
]);7. Architectural Trade-offs
- •$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
- •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
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?