You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计MongoDB aggregate聚合查询返回的所有分组结果的总数量?

MongoDB聚合新增总告警数字段解决方案

方案1:兼容MongoDB 3.4及以上版本

通过$facet算子并行执行两组聚合逻辑,分别计算分组明细和总告警数后合并输出:

db.getCollection('alerts').aggregate([
  {
    $match: {
      houseId: ObjectId("609100a56ed9f8001351aee3")
    }
  },
  {
    $facet: {
      // 原有按告警类型分组的逻辑
      "type_groups": [
        {
          $group: {
            _id: '$type',
            count: { $sum: 1 },
            alerts: {
              $push: {
                _id: '$_id',
                type: '$type'
              }
            }
          }
        }
      ],
      // 计算总告警数
      "total_count": [
        {
          $count: "total"
        }
      ]
    }
  },
  // 展开分组明细
  { $unwind: "$type_groups" },
  // 展开总数
  { $unwind: "$total_count" },
  // 调整输出字段结构
  {
    $project: {
      _id: "$type_groups._id",
      count: "$type_groups.count",
      alerts: "$type_groups.alerts",
      total: "$total_count.total"
    }
  }
])

方案2:MongoDB 5.0及以上版本极简写法

使用窗口函数直接统计全部分组的count总和,无需调整原有聚合逻辑:

db.getCollection('alerts').aggregate([
  {
    $match: {
      houseId: ObjectId("609100a56ed9f8001351aee3")
    }
  },
  {
    $group: {
      _id: '$type',
      count: { $sum: 1 },
      alerts: {
        $push: {
          _id: '$_id',
          type: '$type'
        }
      }
    }
  },
  // 窗口函数计算所有分组的count总和
  {
    $set: {
      total: {
        $sum: "$count",
        $window: {
          documents: ["unbounded", "unbounded"]
        }
      }
    }
  }
])

两种方案输出结果均符合预期,示例返回如下:

[{
    "_id" : "cool",
    "count" : 1.0,
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "cool"
        }
    ],
    "total": 3.0
}, {
    "_id" : "hot",
    "count" : 2.0,
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        },
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        }
    ],
    "total": 3.0
}]

内容的提问来源于stack exchange,提问作者Chicky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:00:01