gpt4 book ai didi

mongodb - 在mongodb的一个聚合中组合多个组

转载 作者:IT老高 更新时间:2023-10-28 13:25:13 25 4
gpt4 key购买 nike

如果我有这样的收藏:

{
"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
}

但是我怎样才能在一个查询中做到这一点呢?

最佳答案

你可以如下聚合:

  • $groupstore字段,计算出subtotal

  • $project 字段 doc 以保持 subtotal 组在下一个组。

  • $group by null 并累计净总数。

代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com