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
Count distinct value in MongoDB?
To count distinct values in MongoDB, use the distinct() method combined with the .length property. This returns the number of unique values for a specified field across all documents in a collection.
Syntax
db.collectionName.distinct("fieldName").length;
Create Sample Data
Let us create a collection with documents that contain duplicate values ?
db.countDistinctDemo.insertMany([
{"StudentName": "John"},
{"StudentName": "Chris"},
{"StudentName": "Chris"},
{"StudentName": "Carol"},
{"StudentName": "David"},
{"StudentName": "Carol"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cbd6166de8cc557214c0dfa"),
ObjectId("5cbd616ade8cc557214c0dfb"),
ObjectId("5cbd616cde8cc557214c0dfc"),
ObjectId("5cbd6170de8cc557214c0dfd"),
ObjectId("5cbd6175de8cc557214c0dfe"),
ObjectId("5cbd6181de8cc557214c0dff")
]
}
Display All Documents
db.countDistinctDemo.find().pretty();
{ "_id": ObjectId("5cbd6166de8cc557214c0dfa"), "StudentName": "John" }
{ "_id": ObjectId("5cbd616ade8cc557214c0dfb"), "StudentName": "Chris" }
{ "_id": ObjectId("5cbd616cde8cc557214c0dfc"), "StudentName": "Chris" }
{ "_id": ObjectId("5cbd6170de8cc557214c0dfd"), "StudentName": "Carol" }
{ "_id": ObjectId("5cbd6175de8cc557214c0dfe"), "StudentName": "David" }
{ "_id": ObjectId("5cbd6181de8cc557214c0dff"), "StudentName": "Carol" }
Count Distinct Values
Apply the distinct count query to get the number of unique student names ?
db.countDistinctDemo.distinct("StudentName").length;
4
The result is 4 because there are 4 unique student names: John, Chris, Carol, and David (duplicates are counted only once).
Conclusion
The distinct().length method efficiently counts unique values in MongoDB by first extracting distinct values and then returning the count. This approach handles duplicates automatically, providing an accurate count of unique field values.
