mongodb 计算每个字段/键的不同值的数量 [英] mongodb count num of distinct values per field/key

查看:42
本文介绍了mongodb 计算每个字段/键的不同值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有用于计算一个字段在 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 运算符检索不同的值,如 使用聚合管道检索不同的值.

Results must not be larger than the maximum BSON size (16MB). If your results exceed the maximum BSON size, use the aggregation pipeline to retrieve distinct values using the $group operator, as described in Retrieve Distinct Values with the Aggregation Pipeline.

这篇关于mongodb 计算每个字段/键的不同值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆