Aggregation Fundamentals
$set and $addFields
Add or overwrite fields without listing every field you want to keep.
$set and $addFields are the same stage. They add or overwrite fields and keep everything else. Use them when $project would force you to re-list name, price, stock, …
db.products.aggregate([
{ $set: { inventoryValue: { $multiply: ["$price", "$stock"] } } }
]){ _id: ObjectId("…"), name: "Mechanical Keyboard", price: 4500, stock: 20, category: "electronics", inventoryValue: 90000 }Overwrite is allowed: { $set: { price: { $multiply: ["$price", 0.9] } } }. There is no $unset stage by that name in older servers; $project/$unset (4.2+) drops fields. Prefer $set for 'add this for the next stage' and $project for the final API shape.
Interview question
When do you use $set / $addFields instead of $project?
When I want to add or overwrite a field and keep the rest of the document. $project is the final reshape — I would have to name every field I still want. They are not interchangeable if I only list the new field in $project; that field would be almost all I get back.