如果我有这样的收藏:
{
"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
}
但是我怎样才能在一个查询中做到这一点呢?
最佳答案
你可以如下聚合:
$group
由store
字段,计算出subtotal
。$project
字段doc
以保持subtotal
组在下一个 组。$group
bynull
并累计净总数。
代码:
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
}
}
])
输出:
{
"total": 1000,
"result": [{
"_id": "ABC",
"total": 700
}, {
"_id": "XYZ",
"total": 300
}
]
}
关于mongodb - 在mongodb的一个聚合中组合多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420631/