问题描述
是否有一个查询来计算一个字段在 DB 中包含多少不同的值.
Is there a query for calculating how many distinct values a field contains in DB.
f.e 我有一个国家字段,国家值有 8 种类型(西班牙、英国、法国等)
f.e I have a field for country and there are 8 types of country values (spain, england, france, etc...)
如果有人添加更多带有新国家/地区的文档,我希望查询返回 9.
If someone adds more documents with a new country I would like the query to return 9.
还有比分组计数更简单的方法吗?
Is there easier way then group and count?
推荐答案
MongoDB 有一个 distinct
命令,它返回一个字段的不同值的数组;您可以检查数组的长度以进行计数.
MongoDB has a distinct
command which returns an array of distinct values for a field; you can check the length of the array for a count.
有一个shell db.collection.distinct()
助手也是:
There is a shell db.collection.distinct()
helper as well:
> db.countries.distinct('country');
[ "Spain", "England", "France", "Australia" ]
> db.countries.distinct('country').length
4
如 MongoDB 文档中所述:
As noted in the MongoDB documentation:
结果不得大于最大 BSON 大小 (16MB).如果您的结果超过最大 BSON 大小,请使用聚合管道使用 $group
运算符检索不同的值,如 使用聚合管道检索不同的值.
这篇关于mongodb count 每个字段/键的不同值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!