**How to count distinct values in a field in MongoDB?**

In MongoDB, you can count distinct values in a field by using the db.collection.distinct() method. This method takes in a field name and returns an array of all the distinct values in that field. You can then use the length of the array to determine the number of distinct values in the 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' ]

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 .

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

x