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

时间:2018-03-15 04:14:00

标签: mongodb

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

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

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

1 个答案:

答案 0 :(得分:1)

我假设您要对class_id进行分组,并将得分类型为exam的所有得分相加。这是一个简单的聚合查询

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

输出:

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