【问题标题】:How to use match and sum together in MongoDB?如何在 MongoDB 中同时使用匹配和求和?
【发布时间】:2021-03-22 12:09:58
【问题描述】:

我有字段,idgroup_idrevenueaccount。我想做一个聚合,收入按id 分组,与特定的group_id 匹配并总结。但是会有两个总和,一个是 account 是空白的,另一个是 account 不是空白的。我该怎么做呢?这是我到目前为止所尝试的。

res = await col.aggregate([
  { $match: { group_id: "ABC" } },
  { $group: { 
    _id: "$id",
    account: { $first: '$account' },
    total_revenue: { $sum: "$revenue" }, //should be for non-empty account
    total_gl: { $sum: "$revenue" } // should be for empty account
  } }
])

【问题讨论】:

    标签: javascript mongodb mongodb-query aggregation-framework


    【解决方案1】:

    演示 - https://mongoplayground.net/p/bVQh1aOEdvb

    使用$filter获取单独的数据

    db.collection.aggregate([
      {
        $match: {
          group_id: "ABC"
        }
      },
      {
        "$group": {
          _id: "$id",
          group_id: {
            $first: "$group_id"
          },
          account: {
            $first: "$account"
          },
          revenue: {
            "$push": {
              "revenue": "$revenue",
              "account": "$account"
            }
          }
        }
      },
      {
        "$project": {
          _id: 0,
          group_id: 1,
          account: 1,
          total_revenue: {
            $filter: {
              input: "$revenue",
              as: "item",
              cond: {
                $ne: [
                  {
                    $type: "$$item.account"
                  },
                  "missing"
                ]
              }
            }
          },
          total_gl: {
            $filter: {
              input: "$revenue",
              as: "item",
              cond: {
                $eq: [
                  {
                    $type: "$$item.account"
                  },
                  "missing"
                ]
              }
            }
          }
        }
      },
      {
        "$project": {
          group_id: 1,
          account: 1,
          total_revenue: {
            $sum: "$total_revenue.revenue"
          },
          total_gl: {
            $sum: "$total_gl.revenue"
          }
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2022-12-01
      • 1970-01-01
      • 2018-07-02
      • 2022-08-18
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多