MongoDB聚合框架:如何按指定前缀对数据分组统计?
MongoDB聚合实现指定前缀分组统计
这个需求完全可以通过MongoDB聚合框架实现,核心思路是通过正则匹配判断code字段的前缀,再按匹配结果分组统计。
聚合管道代码
db.collection.aggregate([ { $group: { _id: { $cond: { if: { $regexMatch: { input: "$code", regex: /^LAZA/ } }, then: "LAZA", else: { $cond: { if: { $regexMatch: { input: "$code", regex: /^LAZ/ } }, then: "LAZ", else: null } } } }, count: { $sum: 1 } } }, { $match: { _id: { $ne: null } } } ])
代码说明
- $group阶段:
- 用嵌套的
$cond逻辑结合$regexMatch做前缀判断:优先匹配以LAZA开头的code,将其分组key设为LAZA; - 未匹配
LAZA的文档,再判断是否以LAZ开头,分组key设为LAZ; - 不满足上述条件的文档分组key设为
null,后续过滤。
- 用嵌套的
- $match阶段:过滤掉分组key为
null的结果,只保留目标分组。
输出结果
执行后会得到你需要的统计结果:
[ { "_id": "LAZ", "count": 2 }, { "_id": "LAZA", "count": 2 } ]
内容的提问来源于stack exchange,提问作者Duy Cao Thiện
相关产品推荐
相关产品推荐

