Get Distinct Values with Sorted Data in MongoDB?

To get distinct values with sorted data in MongoDB, use the distinct() method followed by sort(). The distinct() method returns unique values from a specified field, and sort() arranges them in alphabetical or numerical order.

Syntax

db.collection.distinct("fieldName").sort()

Sample Data

db.getDistinctWithSortedDataDemo.insertMany([
    {"StudentId": 10, "StudentName": "John", "StudentAge": 23},
    {"StudentId": 20, "StudentName": "Carol", "StudentAge": 21},
    {"StudentId": 10, "StudentName": "John", "StudentAge": 23},
    {"StudentId": 30, "StudentName": "Chris", "StudentAge": 22},
    {"StudentId": 20, "StudentName": "Carol", "StudentAge": 21},
    {"StudentId": 40, "StudentName": "Bob", "StudentAge": 20},
    {"StudentId": 40, "StudentName": "Bob", "StudentAge": 20}
]);

View Sample Data

db.getDistinctWithSortedDataDemo.find()
[
    { "_id": ObjectId("..."), "StudentId": 10, "StudentName": "John", "StudentAge": 23 },
    { "_id": ObjectId("..."), "StudentId": 20, "StudentName": "Carol", "StudentAge": 21 },
    { "_id": ObjectId("..."), "StudentId": 10, "StudentName": "John", "StudentAge": 23 },
    { "_id": ObjectId("..."), "StudentId": 30, "StudentName": "Chris", "StudentAge": 22 },
    { "_id": ObjectId("..."), "StudentId": 20, "StudentName": "Carol", "StudentAge": 21 },
    { "_id": ObjectId("..."), "StudentId": 40, "StudentName": "Bob", "StudentAge": 20 },
    { "_id": ObjectId("..."), "StudentId": 40, "StudentName": "Bob", "StudentAge": 20 }
]

Example 1: Distinct Student Names (Sorted)

db.getDistinctWithSortedDataDemo.distinct("StudentName").sort()
[ "Bob", "Carol", "Chris", "John" ]

Example 2: Distinct Student Ages (Sorted)

db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort()
[ 20, 21, 22, 23 ]

Key Points

  • distinct() eliminates duplicate values and returns only unique entries.
  • sort() arranges the distinct values in ascending order automatically.
  • String values are sorted alphabetically, numeric values are sorted numerically.

Conclusion

Using distinct().sort() is an efficient way to get unique values from any field in sorted order. This approach removes duplicates first, then sorts the remaining unique values.

Updated on: 2026-03-15T00:31:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements