MongoDB: How to Count Distinct Values in Field


You can use the following methods to count the distinct values in a specific field in MongoDB:

Method 1: Find List of Distinct Values

db.collection.distinct('field_name')

Method 2: Find Count of Distinct Values

db.collection.distinct('field_name').length

The following examples show how to use each method with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Mavs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})
db.teams.insertOne({team: "Rockets", position: "Forward", points: 26})
db.teams.insertOne({team: "Cavs", position: "Guard", points: 33})

Example 1: Find List of Distinct Values

We can use the following code to find a list of distinct values in the “team” field:

db.teams.distinct('team')

This query returns the following result:

[ 'Cavs', 'Mavs', 'Rockets' ]

The output shows the three distinct team names from all of the documents.

We could also use the following code to find a list of distinct values in the “position” field:

db.teams.distinct('position')

This query returns the following result:

[ 'Center', 'Forward', 'Guard' ]

Note: MongoDB sorts the distinct values in alphabetical order by default.

Example 2: Find Count of Unique Values

We can use the following code to count the number of distinct values in the “team” field:

db.teams.distinct('team').length

This query returns the following result:

3

This tells us that there are 3 distinct values in the “team” field.

We can also use the following code to count the number of unique values in the “points” field:

db.teams.distinct('points').length

This query returns the following result:

5

This tells us that there are 5 distinct values in the “points” field.

Note: You can find the complete documentation for the distinct function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Group By and Count
MongoDB: How to Group By Multiple Fields
MongoDB: How to Find the Max Value in a Collection

Leave a Reply

Your email address will not be published.