首页 > 解决方案 > MongoDb:如何将 Group by 的总计数作为平面计数而不是数组?

问题描述

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

工作 MongoDb 游乐场

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但我想知道这是否可以在本地完成?

标签: javascriptnode.jsmongodbmongodb-queryaggregation-framework

解决方案


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

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

蒙戈游乐场


推荐阅读