在MongoDb中聚合嵌入在值列表中的文档

问题描述 投票:0回答:2

我有MongoDb数据如下

{
        "_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的新手,并试图通过解决一些运动问题来学习。

谢谢

mongodb nosql aggregation-framework
2个回答
1
投票

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

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

0
投票

我已经浏览了MongoDb文档并提出了以下解决方案

  db.students.aggregate([ 
   {$unwind: "$scores"},
   {$match:{"scores.type" : "homework"}},
   {$group : {"_id":"$_id", "score":{$sum: "$scores.score"}}}
 ])
© www.soinside.com 2019 - 2024. All rights reserved.