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

MongoDB单聚合实现多字段分组的方法咨询

在MongoDB中一次聚合完成多字段分组统计

现有MongoDB数据如下:

[
    {
        _id: ObjectId(),
        level: 'High',
        country: 'Palestine'
    },
    {
        _id: ObjectId(),
        level: 'Low',
        country: 'Jordan'
    },
    {
        _id: ObjectId(),
        level: 'High',
        country: 'Jordan'
    }
]

你已经可以通过以下聚合按level字段分组统计:

{
    $group: {
        _id: '$level',
        count: { $sum: 1 }
    }
}

得到结果:

[
    {
        _id: 'High',
        count: 2
    },
    {
        _id: 'Low',
        count: 1
    }
]

针对你需要同时对country及其他多字段完成分组统计的需求,完全可以在一次聚合操作中实现,无需为每个字段单独执行分组。MongoDB的$facet阶段可以实现类似Elasticsearch的多聚合逻辑。

完整聚合管道示例

db.collection.aggregate([
    {
        $facet: {
            "level_stats": [
                { $group: { _id: "$level", count: { $sum: 1 } } }
            ],
            "country_stats": [
                { $group: { _id: "$country", count: { $sum: 1 } } }
            ]
            // 如需统计更多字段,直接添加新的子聚合管道即可
            // "other_field_stats": [
            //     { $group: { _id: "$other_field", count: { $sum: 1 } } }
            // ]
        }
    }
])

执行结果

上述聚合会返回整合了所有统计结果的文档,结构如下:

{
    "level_stats": [
        { "_id": "High", "count": 2 },
        { "_id": "Low", "count": 1 }
    ],
    "country_stats": [
        { "_id": "Palestine", "count": 1 },
        { "_id": "Jordan", "count": 2 }
    ]
}

核心说明

  • $facet阶段允许在单次聚合中定义多个独立的子聚合管道,每个管道对应一个字段的统计需求,最终将所有管道的结果整合到同一个文档返回。
  • 若需要统计更多字段,只需在$facet中新增键值对,值为对应字段的$group聚合数组即可,无需重复执行聚合操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:22:52