javascript - MongoDb:如何将 Group by 的总计数作为平面计数而不是数组?
问题描述
这对我来说很难用语言表达,所以我将尝试用一个代码示例来解释:
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
但我想知道这是否可以在本地完成?