MongoDB $set
Add or replace fields while keeping the rest of the document.
Use it when the next stage needs a calculated value but you still want every existing field to remain available. `$set` is an alias for `$addFields`.
Stages are the top-level steps in a pipeline. Each stage receives documents, changes the stream in one specific way, and passes its output to the next stage.
Course use: Exercises 04, 06, 12, and Hard Mode 13.
Example pipeline syntax { $set: { itemCount: { $sum: "$items.qty" } } }
Continue learning Challenge 06: Measure each basket Add an `itemCount` field containing the total quantity across each order’s items. Challenge 08: Classify priority orders Add `priority: "high"` when total is at least 200; otherwise add `priority: "standard"`. Challenge 09: Calculate every line total Add a `lineTotals` array to every order. Each entry must equal that item’s quantity multiplied by its unit price. Challenge 18: Map regional category leaders Using completed orders, calculate line revenue, join product categories, total revenue by region and category, then return every region-category pair ranked by revenue. Challenge 21: Build the commerce command report For completed orders, return one document with three arrays. `categoryPerformance` contains the top three categories with `category`, `revenue`, and `units`. `segmentPerformance` contains every customer segment with `segment`, `revenue`, `orderCount`, and `averageOrder`. `topOrder` contains the largest order with `orderId`, `region`, and `total`. Sort every report by revenue or total descending, using its name as the tie-breaker. Challenge 24: Roll up a monthly revenue series For completed orders, calculate monthly revenue and order count. Return `month`, `revenue`, and `orderCount` in chronological order. Challenge 25: Tune a lean category report For completed web orders, report revenue by region and product category. `$match` must run first, `$project` must trim documents before `$lookup`, and the complete pipeline must use no more than nine stages. Official MongoDB $set documentation Browse all aggregation operators