MongoDB中如何仅统计字段值的唯一出现次数?
统计字段唯一值的数量(去重后计数)
需求说明
需要统计数组/集合中指定字段的唯一值个数(每个值仅统计一次),示例数据如下:
[ {name: 'a', otherStuff: 'blah'}, {name: 'a', otherStuff: 'blah'}, {name: 'b', otherStuff: 'blah'}, {name: 'c', otherStuff: 'blah'}, {name: 'c', otherStuff: 'blah'}, {name: 'a', otherStuff: 'blah'} ]
期望得到结果:
{ names_count: 3 }
解决方案
1. JavaScript 环境处理
利用Set的天然去重特性,提取目标字段值后直接获取去重后的长度:
const data = [/* 上述示例数据 */]; const uniqueNames = new Set(data.map(item => item.name)); const result = { names_count: uniqueNames.size }; console.log(result); // 输出 { names_count: 3 }
2. MongoDB 聚合查询(数据库场景)
你之前尝试的分组思路没问题,但需要补充统计分组数量的步骤:
db.yourCollectionName.aggregate([ // 按name字段分组,每个唯一name生成一个独立分组 { $group: { _id: "$name" } }, // 统计分组总数,即唯一name的数量 { $count: "names_count" } ])
执行后会直接返回{ "names_count" : 3 }。之前分组失败大概率是只完成了分组操作,没加上后续的计数步骤,或是错误统计了分组内的文档数而非分组本身的数量。
内容的提问来源于stack exchange,提问作者Santos
相关产品推荐
相关产品推荐

