MongoDb中的Aggreate,用于嵌入值列表中的文档

时间:2018-09-04 14:38:26

标签: mongodb nosql aggregation-framework

我在MongDb中具有以下数据

{
        "_id" : 7,
        "name" : "Salena Olmos",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 90.37826509157176
                },
                {
                        "type" : "quiz",
                        "score" : 42.48780666956811
                },
                {
                        "type" : "homework",
                        "score" : 67.18328596625217
                },
                {
                        "type" : "homework",
                        "score" : 96.52986171633331
                }
        ]
}

所有我想将“类型”:“作业”的“分数”总和为

{ "_id" : 7, "score" : 163.71314768258548} 

我使用以下汇总和过滤条件编写了查询

db.students.aggregate([
    {     
     "$group" : 
      { 
       "_id":"$_id",
       "score":{$sum: {$filter: {
                                input: "$scores",
                                    as: "x",
                                cond: {$eq : ["$$x.type", "homework"]}
                                }
                      }
               }
      }
    }
])

但所有这些使我的总和为“ 0”:

{ "_id" : 7, "score" : 0 }

请帮助我,我是MongoDb的新手,正尝试通过解决一些运动问题来学习。

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用以下汇总。使用$let从匹配分数中提取分数。

db.students.aggregate({
  "$project":{
    "score":{
      "$sum":{
        "$let":{
          "vars":{
            "mscores":{
              "$filter":{
                "input":"$scores",
                "as":"x",
                "cond":{"$eq":["$$x.type","homework"]}
              }
            }
          },
          "in":"$$mscores.score"
        }
      }
    }
  }
})

答案 1 :(得分:0)

我阅读了MongoDb文档,并提出了以下解决方案

  db.students.aggregate([ 
   {$unwind: "$scores"},
   {$match:{"scores.type" : "homework"}},
   {$group : {"_id":"$_id", "score":{$sum: "$scores.score"}}}
 ])
相关问题