0

For example I have the following data in MongoDB:

  {
    "student": "Pedro",
    "class_id": 10,
    "scores": [
             {
                "type":"exam",
                "score": 10  
             },
             {
                "type":"homework",
                "score": 10  
             }
     ] 
  }

Now I want to query "SUM the scores - score", how could I do this using Mongo Shell?

Danny
  • 47
  • 11

1 Answers1

1

You can use $reduce which transforms an array to a scalar value:

db.col.aggregate([
    {
        $project: {
            student: 1,
            class_id: 1,
            totalScore: {
               $reduce: {
                  input: "$scores",
                  initialValue: 0,
                  in: { $add : ["$$value", "$$this.score"] }
               }
            }
        }
    }
])
mickl
  • 48,568
  • 9
  • 60
  • 89