gpt4 book ai didi

java - 具有线性分布的 Group 和 Sum MongoDb 聚合框架

转载 作者:行者123 更新时间:2023-11-29 04:22:37 25 4
gpt4 key购买 nike

我必须按 myArray 的值进行分组,并用线性属性对总和求和,这意味着对于这两个文档,我们应该对所有值的总值进行线性分布:

/* 1 */
{
"_id" : ObjectId("5a535c48a4d86ed94a7e8618"),
"total" : 5.8,
"myArray" : [
{
"value" : "a"
},
{
"value" : "b
},
{
"value" : "a"
},
{
"value" : "c"
},
{
"value" : "a"
},
{
"value" : "a"
}
]
}


/* 2 */
{
"_id" : ObjectId("5a535c48a4d86ed94a7e8619"),
"total" : 4.5,
"myArray" : [
{
"value" : "a"
},
{
"value" : c"
},
{
"value" : "c"
}
]
}

在这个例子中我们必须得到:

"a" -> 4/6 * 5.8 + 1/3 * 4.5 / "b" -> 1/6*5.8 +0*4.5 / "c" -> 1/6*5.8 + 2/3*4.5 

结果必须是这样的:

 [
{
"_id": "a",
"linear_total": 4/6 * 5.8 + 1/3 * 4.5
},
{
"_id": "b",
"linear_total": 1/6*5.8 +0*4.5
},
{
"_id": "c",
"linear_total": 1/6*5.8 + 2/3*4.5
}
]

我不知道这是否是聚合中的可用功能,可以计算数组中值的分布,因此我可以轻松地乘以总数和总和 .. 或者您对如何实现它有任何想法。非常感谢

最佳答案

这会起作用:

db.collection.aggregate([
{
$project: {
_id: 1,
total: 1,
myArray: 1,
arraySize: { $size: "$myArray"} // count the size of your array
}
},
{
$unwind: "$myArray" // flatten your array
},
{
$group: {
_id: {id: "$_id", value: "$myArray.value"},
total: { $first: "$total"},
myArray: { $first: "$myArray"},
arraySize: { $first: "$arraySize" },
countVal: { $sum: 1} // count the occurrence of value out of total array size in each document
}
},
{
$project: {
_id: 1,
divmulti: { "$multiply": [ { "$divide": ["$countVal","$arraySize"] }, "$total" ] }
}
},
{
$group: {
_id: "$_id.value", // group by value
"linear_total": { $sum: "$divmulti" } // and some the results
}
}
])

在这个例子中,你会得到这样的结果:

{ 
"_id" : "c",
"linear_total" : 3.966666666666667
}
{
"_id" : "b",
"linear_total" : 0.9666666666666666
}
{
"_id" : "a",
"linear_total" : 5.366666666666666
}

关于java - 具有线性分布的 Group 和 Sum MongoDb 聚合框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48164974/

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