If I have a collection like this:
{
\"store\" : \"XYZ\",
\"total\" : 100
},
{
\"store\" : \"XYZ\",
\"total\" : 200
},
{
\"store\" : \"ABC
You could aggregate as below:
$group
by the store
field, calculate the subtotal
.
$project
a field doc
to keep the subtotal
group in tact, during the next
group.
$group
by null
and accumulate the net total.
Code:
db.invoices.aggregate([{
$group: {
"_id": "$store",
"subtotal": {
$sum: "$total"
}
}
}, {
$project: {
"doc": {
"_id": "$_id",
"total": "$subtotal"
}
}
}, {
$group: {
"_id": null,
"total": {
$sum: "$doc.total"
},
"result": {
$push: "$doc"
}
}
}, {
$project: {
"result": 1,
"_id": 0,
"total": 1
}
}
])
Output:
{
"total": 1000,
"result": [{
"_id": "ABC",
"total": 700
}, {
"_id": "XYZ",
"total": 300
}
]
}