MongoDB:在嵌套文档中$match查询



我正在尝试匹配文档数组中的某些值。但我没有运气去做。这是文档:

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

我想匹配分数.分数在哪里是考试,我试过这个

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

但它不起作用,有什么建议吗?

我假设您想对class_id进行分组,并对分数类型exam的所有分数求和。下面是一个简单的聚合查询

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

输出:

{ "_id" : 10, "sumOfScores" : 10 }

最新更新