Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to count number of distinct values per field/ key in MongoDB?
To count the number of distinct values per field in MongoDB, use the distinct() method combined with the .length property. The distinct() method returns an array of unique values from a specified field across all documents.
Syntax
db.collection.distinct("fieldName").length
Sample Data
Let's create a collection with student documents containing favorite subjects ?
db.distinctCountValuesDemo.insertMany([
{
"StudentFirstName": "John",
"StudentFavouriteSubject": ["C", "C++", "Java", "MySQL", "C", "C++"]
},
{
"StudentFirstName": "Larry",
"StudentFavouriteSubject": ["MongoDB", "SQL Server"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8a39f193b406bd3df60e07"),
ObjectId("5c8a3a1193b406bd3df60e08")
]
}
Example: Count Distinct Values
First, let's see all documents in the collection ?
db.distinctCountValuesDemo.find().pretty();
{
"_id": ObjectId("5c8a39f193b406bd3df60e07"),
"StudentFirstName": "John",
"StudentFavouriteSubject": [
"C",
"C++",
"Java",
"MySQL",
"C",
"C++"
]
}
{
"_id": ObjectId("5c8a3a1193b406bd3df60e08"),
"StudentFirstName": "Larry",
"StudentFavouriteSubject": [
"MongoDB",
"SQL Server"
]
}
Now, get all distinct values from the StudentFavouriteSubject field ?
db.distinctCountValuesDemo.distinct('StudentFavouriteSubject');
["C", "C++", "Java", "MySQL", "MongoDB", "SQL Server"]
Finally, count the number of distinct values by adding .length ?
db.distinctCountValuesDemo.distinct('StudentFavouriteSubject').length;
6
Key Points
- The
distinct()method automatically removes duplicate values from arrays and across documents. - Use
.lengthproperty to get the count of unique values. - Works with both single values and array fields.
Conclusion
Use db.collection.distinct('fieldName').length to count unique values per field in MongoDB. This method efficiently handles duplicates and provides the total count of distinct values across all documents in the collection.
