gpt4 book ai didi

Mongodb groupby on Dictionary inside dictionary

转载 作者:可可西里 更新时间:2023-11-01 10:08:57 40 4
gpt4 key购买 nike

我有一个集合,其中包含如下文档:文档 1:

{
"company": "ABC"
"application": {
"app-1": {"earning_from_src_A": 50,
"earning_from_src_B": 43},
"app-2": {"earning_from_src_A": 10,
"earning_from_src_B": 13}
}
}

文件 2:

{
"company": "ABCD"
"application": {
"app-1": {"earning_from_src_A": 150,
"earning_from_src_B": 413},
"app-2": {"earning_from_src_A": 110,
"earning_from_src_B": 113},
"app-3": {"earning_from_src_A": 1,
"earning_from_src_B": 34},
}
}

我想获取所有集合文档的应用程序总和。喜欢:结果:

{
"app-1": {"earning_from_src_A": 200,
"earning_from_src_B": 456},
"app-2": {"earning_from_src_A": 120,
"earning_from_src_B": 126},
"app-3": {"earning_from_src_A": 1,
"earning_from_src_B": 34},
}

谁能帮我解决这个问题?

我尝试使用聚合函数,但我无法对整个集合进行分组。

最佳答案

您可以使用以下聚合

所以基本上你的 key 在这里是未知的。因此,您必须使用 $objectToArray 聚合将它们转换为键值对。然后,您可以使用应用程序名称轻松地 $group 他们,并计算从 AB 获得的收入。

db.collection.aggregate([
{ "$addFields": {
"application": { "$objectToArray": "$application" }
}},
{ "$unwind": "$application" },
{ "$group": {
"_id": "$application.k",
"earning_from_src_A": {
"$sum": "$application.v.earning_from_src_A"
},
"earning_from_src_B": {
"$sum": "$application.v.earning_from_src_B"
}
}},
{ "$group": {
"_id": null,
"data": {
"$push": {
"k": "$_id",
"v": {
"earning_from_src_A": "$earning_from_src_A",
"earning_from_src_B": "$earning_from_src_B"
}
}
}
}},
{ "$replaceRoot": { "newRoot": { "$arrayToObject": "$data" }}}
])

哪个 outputs

[
{
"app-1": {
"earning_from_src_A": 200,
"earning_from_src_B": 456
},
"app-2": {
"earning_from_src_A": 120,
"earning_from_src_B": 126
},
"app-3": {
"earning_from_src_A": 1,
"earning_from_src_B": 34
}
}
]

关于Mongodb groupby on Dictionary inside dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53692989/

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