汇总管道计数总和

时间:2018-09-05 17:51:48

标签: mongodb mongodb-query aggregation-framework

我对汇总有疑问。我不知道或不知道如何构建它。这是我的收藏:

{
"_id": ObjectId("5b900efbb9440c000646f803"),
"status": 0,
"date": NumberLong(0),
"player1": {
    "name": "",
    "sets": [{
        "points": [{
            "score": 0,
            "comment": "sa"
        }, {
            "score": 1,
            "comment": "sw"
        }, {
            "score": 2,
            "comment": "sw"
        }]
    }]
},
"player2": {
    "name": "",
    "sets": [{
        "points": [{
            "score": 0,
            "comment": ""
        }, {
            "score": 1,
            "comment": "fh"
        }, {
            "score": 2,
            "comment": "sw"
        }]
    }]
}}

我如何计算评论为“ sw”的玩家1的积分总和?

谢谢。请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总。

使用$filter过滤点comment ='sw'后跟$size的点以计数每个点数组中的匹配项。使用$map来执行所有集合的逻辑,并使用$sum来计算所有集合中的所有匹配项

db.colname.aggregate([
  {"$match":{"player1.name":"","player2.name":""}},
  {"$project":{
    "count":{
      "$add":[
        {"$sum":{
          "$map":{
            "input":"$player1.sets",
            "as":"set",
            "in":{
              "$size":{
                "$filter":{"input":"$$set.points","cond":{"$eq":["$$this.comment","sw"]}}
              }
            }
          }
        }},
        {"$sum":{
          "$map":{
            "input":"$player2.sets",
            "as":"set",
            "in":{
              "$size":{
                "$filter":{"input":"$$set.points","cond":{"$eq":["$$this.comment","sw"]}}
              }
            }
          }
        }}
      ]
    }
  }}
])

答案 1 :(得分:0)

我认为这可以解决问题:

db.colname.aggregate(
{
    { $unwind: "$player1.sets" },
    { $unwind: "$player1.sets.points" },
    { $match: { player1.sets.points.comment: "sw" },
    {
        $group : {
           _id : null,
           total: { $sum: $player1.sets.points.comment },
        }
    }
})