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

如何编写MongoDB聚合查询实现类似SQL的GROUP BY COUNT统计

实现MongoDB按agency和statusResidence分组统计的查询

要实现你需要的类似SQL的分组统计效果,核心是先把嵌套的residents数组展开,再进行分组计数,正确的聚合查询如下:

db.interviews.aggregate([
  // 展开residents数组,每个数组元素生成独立文档
  { $unwind: "$residents" },
  // 按agency和residents.statusResident分组,统计数量
  {
    $group: {
      _id: {
        agency: "$agency",
        statusResident: "$residents.statusResident"
      },
      total: { $sum: 1 }
    }
  },
  // 调整输出格式,让结果更直观
  {
    $project: {
      _id: 0,
      agency: "$_id.agency",
      statusResident: "$_id.statusResident",
      total: 1
    }
  },
  // 按agency排序,和预期结果顺序一致
  { $sort: { agency: 1 } }
])

为什么你之前的查询不生效?

  • 第一个聚合查询里,直接用$residents.statusResident会得到一个数组(比如AG1对应的是["pending", "not analyzed", "not analyzed", "finished"]),没法作为分组key进行统计,而且$sum的用法也错误,不能直接sum数组字段。
  • group()方法本身不支持自动展开嵌套数组,指定"residents.statusResident":1作为key时,会把整个数组作为分组依据,而不是每个元素单独分组,所以统计结果完全不符合预期。

执行上述正确查询后,会返回和你预期一致的结果:

{ "agency" : "AG1", "statusResident" : "pending", "total" : 1 }
{ "agency" : "AG1", "statusResident" : "not analyzed", "total" : 2 }
{ "agency" : "AG1", "statusResident" : "finished", "total" : 1 }
{ "agency" : "AG2", "statusResident" : "pending", "total" : 1 }
{ "agency" : "AG2", "statusResident" : "not analyzed", "total" : 1 }

内容的提问来源于stack exchange,提问作者Rogério Arantes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:15:27