如何在Mongodb中汇总$ sum和$ filter(组)

时间:2019-07-17 11:53:12

标签: node.js mongodb mongoose aggregation-framework

尝试将上述数据与组汇总相加总是返回0。

{
     team: "5d091e8b402c1d089042000d"
     _id: "5d2e63ce89be227d171eb4a7"
     goals: [
      {
        player: "5d20636a4b0bf2670c1e014c"
        createdAt: "1970-01-01T00:18:31.111+00:00"
        value: 1
        _id: 5d2e63ce89be227d171eb4aa
      },
      {
        player: "5d20636a4b0bf2670c1e014c"
        createdAt: "1970-01-01T00:18:31.111+00:00"
        value: 1
        _id: 5d2e63ce89be227d171eb4aa
      }
     ]
    }

    {
     team: "5d091e8b402c1d089042000d"
     _id: "5d2e63ce89be227d171eb4a7"
     goals: [
      {
        player: "5d20636a4b0bf2670c1e014c"
        createdAt: "1970-01-01T00:18:31.111+00:00"
        value: 1
        _id: 5d2e63ce89be227d171eb4aa
      },
      {
        player: "5d20636a4b0bf2670c1e014c"
        createdAt: "1970-01-01T00:18:31.111+00:00"
        value: 1
        _id: 5d2e63ce89be227d171eb4aa
      }
     ]
    }

当前尝试:

{
  _id: "$team",
    total: { 
      "$sum": {
        "$filter": {
            "input": "$goals", 
            "as": "s",
            "cond": { "$eq": [ "$$s.player", "5d20636a4b0bf2670c1e014c"] }
        }  
      }
    }
}

以上返回:

{ _id: 5d20636a4b0bf2670c1e014c, total: 0}

enter image description here

1 个答案:

答案 0 :(得分:1)

将过滤移到一个单独的管道阶段然后再运行两次$sum(内部一个将单个文档的数组求和,外部聚合跨文档的值)会更容易

db.collection.aggregate([
    {
        $addFields: {
            goals: {
                $filter: {
                    input: "$goals",
                    as: "g",
                    cond: {
                        $eq: [ "$$g.player", "5d20636a4b0bf2670c1e014c" ]
                    }
                }
            }
        }
    },
    {
        $group: {
            _id: "$team",
            total: { $sum: { $sum: "$goals.value" } }
        }
    }
])

Mongo Playground