本文介绍了在mongodb的一个聚合中组合多个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的收藏:
{
"store" : "XYZ",
"total" : 100
},
{
"store" : "XYZ",
"total" : 200
},
{
"store" : "ABC",
"total" : 300
},
{
"store" : "ABC",
"total" : 400
}
我可以通过聚合得到集合中订单的$sum
:
I can get the $sum
of orders in the collection by aggregation:
db.invoices.aggregate([{$group: { _id: null, total: { $sum: "$total"}}}])
{
"result": [{
"_id": null,
"total": 1000
}
],
"ok": 1
}
我可以得到按商店分组的订单的$sum
:
And I can get the $sum
of orders grouped by store:
db.invoices.aggregate([{$group: { _id: "$store", total: { $sum: "$total"}}}])
{
"result": [{
"_id": "ABC",
"total": 700
}, {
"_id": "XYZ",
"total": 300
}
],
"ok": 1
}
但是我怎样才能在一个查询中做到这一点呢?
But how can I do this in one query?
推荐答案
你可以聚合如下:
$group
由store
字段,计算出subtotal
.
$project
字段 doc
以保持 subtotal
组在下一个组.
$project
a field doc
to keep the subtotal
group in tact, during the nextgroup.
$group
by null
并累计净总数.
$group
by null
and accumulate the net total.
代码:
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的一个聚合中组合多个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!