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

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

问题描述

是否存在用于计算字段在数据库中包含多少个不同值的查询.

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.

还有一个外壳 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计算每个字段/键的不同值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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