Find sum of fields inside array in MongoDB

2020-04-17 06:34发布

问题:

I have a data as follows:

> 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
            }
    ]
}

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" }
  }
}])

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.

Please can someone help me. I am new to MongoDB (quite evident though).

回答1:

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"
    }
  }}
])