Filter first, then group and sum.
Section: Core stages
Sum revenue by status
javascript
javascript
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$country", revenue: { $sum: "$total" }, orders: { $sum: 1 } } },
{ $sort: { revenue: -1 } }
])Explanation
`$match` early in the pipeline can reduce the amount of work later stages perform.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Core stages
Join with another collection
Use `$lookup` for collection-to-collection joins.
Run multiple result sets with $facet
Produce multiple related aggregations in one pipeline.
Count pipeline output
Return a final count after filters and transforms.