0

I'm trying to match some values in an array of documents. But i got no luck to do it. This is the document:

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

I want to match the scores.score where is an exam, i have tried this

db.class.aggregate(
             {
                $unwind: "$scores"
             },
             {
                $group: {
                      _id: "$class_id"
                }
             }, 
             {
                $match:{
                      "$scores.score": "exam"
                  }
             }
 )

But it doesn't work, any suggestion?

Danny
  • 47
  • 11

1 Answers1

1

I assume you want to group over class_id and sum all the scores where score type is exam. Here is a simple aggregate query

db.collection.aggregate([
   {
      $unwind:"$scores"
   },
   {
      $match:{
         "scores.type":'exam'
      }
   },
   {
      $group:{
         _id:"$class_id",
         sumOfScores:{
            $sum:"$scores.score"
         }
      }
   }
])

Output:

{ "_id" : 10, "sumOfScores" : 10 }
Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37