6. Creating Fields with $set and $addFields
$set and $addFields add or replace fields while preserving other fields in the current document. They are aliases for the same general purpose. Use them to add intermediate calculations without listing every field to retain.
When a field already exists, assigning it in $set replaces its value in the pipeline output. $ifNull can provide a fallback for missing or null fields. A fallback is a business decision: do not automatically convert malformed values to zero when that would hide bad data.
Code Example
db.orders.aggregate([
{
$set: {
itemSubtotal: {
$sum: {
$map: {
input: "$items",
as: "item",
in: { $multiply: ["$$item.quantity", "$$item.price"] }
}
}
},
discountAmount: { $ifNull: ["$discount", 0] },
shippingAmount: { $ifNull: ["$shippingFee", 0] }
}
},
{
$set: {
totalBeforeTax: {
$add: [{ $subtract: ["$itemSubtotal", "$discountAmount"] }, "$shippingAmount"]
}
}
}
]);Key Takeaways
- $set preserves other fields.
- Existing values can be replaced.
- $ifNull handles missing and null values.
- Validate types for important calculations.
Knowledge Check
What does $set do to fields not named in the stage?