Is there a query for calculating how many distinct values a field contains in DB.
f.e I have a field for country and there are 8 types of country values (spain, england, france, etc...)
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 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.There is a shell
db.collection.distinct()
helper as well:Here is example of using aggregation API. To complicate the case we're grouping by case-insensitive words from array property of the document.
that give result such as
With MongoDb 3.4.4 and newer, you can leverage the use of
$arrayToObject
operator and a$replaceRoot
pipeline to get the counts.For example, suppose you have a collection of users with different roles and you would like to calculate the distinct counts of the roles. You would need to run the following aggregate pipeline:
Example Output
You can leverage on Mongo Shell Extensions. It's a single .js import that you can append to your
$HOME/.mongorc.js
, or programmatically, if you're coding in Node.js/io.js too.Sample
For each distinct value of field counts the occurrences in documents optionally filtered by query
The field parameter could be an array of fields
To find distinct in
field_1
in collection but we want someWHERE
condition too than we can do like following :db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})
So, find number distinct
names
from a collection where age > 25 will be like :db.your_collection_name.distinct('names', {'age': {"$gt": 25}})
Hope it helps!