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?

0

1 Answer 1

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"] }
               }
            }
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.