如果我有这样一个集合:
{
"store" : "XYZ",
"total" : 100
},
{
"store" : "XYZ",
"total" : 200
},
{
"store" : "ABC",
"total" : 300
},
{
"store" : "ABC",
"total" : 400
}
我可以通过聚合操作得到集合中订单总额$sum
:
db.invoices.aggregate([{$group: { _id: null, total: { $sum: "$total"}}}])
{
"result": [{
"_id": null,
"total": 1000
}
],
"ok": 1
}
我可以按店铺对订单进行分组,然后获取订单总额$sum
:
db.invoices.aggregate([{$group: { _id: "$store", total: { $sum: "$total"}}}])
{
"result": [{
"_id": "ABC",
"total": 700
}, {
"_id": "XYZ",
"total": 300
}
],
"ok": 1
}
但是我该如何在一次查询中完成呢?
$unwind
,那么情况就会有所不同,因为这是非常昂贵的。 - BatScream