【问题标题】:MongoDb: How to get Group by's total count as a flat count instead of in an array?MongoDb:如何将 Group by 的总计数作为平面计数而不是数组?
【发布时间】:2020-10-15 13:47:43
【问题描述】:

这对我来说很难用语言表达,所以我将尝试用一个代码示例来解释:

Working MongoDb Playground

db.collection.aggregate([
  {
    "$facet": {
      "countByStatus": [
        {
          "$group": {
            "_id": "$status.name",
            "count": {
              "$sum": 1
            }
          }
        }
      ],
      "totalCount": [
        {
          "$group": {
            "_id": null,
            "count": {
              "$sum": 1
            }
          }
        }
      ]
    }
  }
])

输出:

[
  {
    "countByStatus": [
      {
        "_id": "Approved",
        "count": 2
      },
      {
        "_id": "Rejected",
        "count": 1
      }
    ],
    "totalCount": [
      {
        "_id": null,
        "count": 3
      }
    ]
  }
]

期望的输出:

[
  {
    "countByStatus": [
      {
        "_id": "Approved",
        "count": 2
      },
      {
        "_id": "Rejected",
        "count": 1
      }
    ],
    "totalCount": 3 //totalCount is a flat count instead of array here
  }
]

我可以执行查询得到结果,然后选择array[0].count 的第一个元素,但我想知道这是否可以在本地完成?

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    可以用$let在一个阶段完成:

    {
        $project: {
            countByStatus: 1,
            totalCount: {
                $let: {
                    vars: { first: { $arrayElemAt: [ "$totalCount", 0 ] } },
                    in: "$$first.count"
                }
            }
        }
    }
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多