Skip to content

Aggregation Fundamentals

$set and $addFields

Add or overwrite fields without listing every field you want to keep.

IntermediateAbout 4 minutes

$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"] } } }
])
Keyboard still has every original field, plus inventoryValue
{ _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?

Think about it first.