If I have a collection like this:
{
\"store\" : \"XYZ\",
\"total\" : 100
},
{
\"store\" : \"XYZ\",
\"total\" : 200
},
{
\"store\" : \"ABC
Another approach would be using the $facet
aggregation stage.
$facet
allows you to do multiple nested sub-aggregations
within your main aggregation.Like this, for example:
db.invoices.aggregate([
{
$facet: {
total: [
{
$group: {
_id: null,
total: { $sum: "$total"}
}
}
],
store_totals: [
{
$group: {
_id: "$store",
total: { $sum: "$total"}
}
}
]
}
},{
$unwind: "$total"
},{
$project: {
_id: 0,
total: "$total.total",
store_totals: "$store_totals"
}
}
]
@BatScream wrote, that an
$unwind
stage might be costly. However we're unwinding an array of length 1 here. So I'm curious which approach is more efficient under which circumstances. If someone can compare those withconsole.time()
, I'd be happy to include the results.
Should be the same as in the accepted answer.