在MongoDB中查找数组内的字段总和 [英] Find sum of fields inside array in MongoDB
问题描述
我的数据如下:
> db.PQRCorp.find().pretty()
{
"_id" : 0,
"name" : "Ancy",
"results" : [
{
"evaluation" : "term1",
"score" : 1.463179736705023
},
{
"evaluation" : "term2",
"score" : 11.78273309957772
},
{
"evaluation" : "term3",
"score" : 6.676176060654615
}
]
}
{
"_id" : 1,
"name" : "Mark",
"results" : [
{
"evaluation" : "term1",
"score" : 5.89772766299929
},
{
"evaluation" : "term2",
"score" : 12.7726680028769
},
{
"evaluation" : "term3",
"score" : 2.78092882672992
}
]
}
{
"_id" : 2,
"name" : "Jeff",
"results" : [
{
"evaluation" : "term1",
"score" : 36.78917882992872
},
{
"evaluation" : "term2",
"score" : 2.883687879200287
},
{
"evaluation" : "term3",
"score" : 9.882668212003763
}
]
}
我要实现的目标是:: 查找在合计(term1 + term2 + term3)中失败的员工
What I want to achieve is ::Find employees who failed in aggregate (term1 + term2 + term3)
我正在做并最终得到的是:
What I am doing and eventually getting is:
db.PQRCorp.aggregate([
{$unwind:"$results"},
{ $group: {_id: "$id",
'totalTermScore':{ $sum:"$results.score" }
}
}])
输出: {"_id":null,"totalTermScore":90.92894831067625} 简而言之,我得到的是所有分数的固定总和. 我想要的是,分别为单独的员工合计1、2和3.
OUTPUT:{ "_id" : null, "totalTermScore" : 90.92894831067625 } Simply I am getting a output of a flat sum of all scores. What I want is, to sum terms 1 , 2 and 3 separately for separate employees.
请有人可以帮助我.我是MongoDB的新手(虽然很明显).
Please can someone help me. I am new to MongoDB (quite evident though).
推荐答案
您无需在此处使用$unwind
和$group
...一个简单的$project
查询可以$sum
您的整个分数...
You do not need to use $unwind
and $group
here... A simple $project
query can $sum
your entire score...
db.PQRCorp.aggregate([
{ "$project": {
"name": 1,
"totalTermScore": {
"$sum": "$results.score"
}
}}
])
这篇关于在MongoDB中查找数组内的字段总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!