查找 MongoDB 中数组内字段的总和

rah*_*jee 3 mongodb mongodb-query aggregation-framework

我有一个数据如下:

> 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
            }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是 ::查找总计失败的员工(term1 + term2 + term3)

我正在做的并最终得到的是:

db.PQRCorp.aggregate([ 
{$unwind:"$results"},
{ $group: {_id: "$id",
   'totalTermScore':{ $sum:"$results.score" }
  }
}])
Run Code Online (Sandbox Code Playgroud)

OUTPUT: { "_id" : null, "totalTermScore" : 90.92894831067625 } 简而言之,我得到的是所有分数的平和总和的输出。我想要的是,为不同的员工分别对第 1 项、第 2 项和第 3 项求和。

请有人帮助我。我是 MongoDB 的新手(虽然很明显)。

Ash*_*shh 10

你不需要在这里使用$unwindand $group...一个简单的$project查询就可以$sum你的整个分数...

db.PQRCorp.aggregate([
  { "$project": {
    "name": 1,
    "totalTermScore": {
      "$sum": "$results.score"
    }
  }}
])
Run Code Online (Sandbox Code Playgroud)