5. Reshaping Documents with $project
$project controls which fields appear and can calculate new fields, rename fields, and construct nested output documents. In an inclusion-style projection, _id remains included by default unless explicitly excluded. Do not mix inclusion and exclusion modes except for the special handling of _id.
A dollar-prefixed field path such as "$status" references a field in the current pipeline document. Expressions can be nested to calculate totals. Keep any fields required by later stages in the projection.
Define the business formula
An item subtotal is not necessarily net revenue. Discount, shipping, tax, and refund treatment must be defined separately.
Code Example
db.orders.aggregate([
{
$project: {
_id: 1,
customerId: 1,
status: 1,
itemSubtotal: {
$sum: {
$map: {
input: "$items",
as: "item",
in: { $multiply: ["$$item.quantity", "$$item.price"] }
}
}
},
shippingFee: { $ifNull: ["$shippingFee", 0] }
}
}
]);Key Takeaways
- $project shapes output fields.
- Field paths use a dollar prefix.
- _id is included by default.
- Keep fields required by later stages.
Knowledge Check
What does "$price" mean in an aggregation expression?