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.

Updated on: 2026-03-15T00:50:27+05:30

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements