How to do alphanumeric sort in MongoDB?

To perform alphanumeric sort in MongoDB, use the collation method with numericOrdering: true. This ensures that numeric portions within strings are sorted numerically rather than lexically (e.g., "STU101" comes before "STU1010").

Syntax

db.collection.find().sort({field: 1}).collation({
    locale: "en_US", 
    numericOrdering: true
});

Sample Data

db.alphanumericSortDemo.insertMany([
    {"StudentId": "STU1010"},
    {"StudentId": "STU1101"},
    {"StudentId": "STU1901"},
    {"StudentId": "STU908"},
    {"StudentId": "STU101"}
]);

Display all documents to see the insertion order ?

db.alphanumericSortDemo.find();
{ "_id": ObjectId("..."), "StudentId": "STU1010" }
{ "_id": ObjectId("..."), "StudentId": "STU1101" }
{ "_id": ObjectId("..."), "StudentId": "STU1901" }
{ "_id": ObjectId("..."), "StudentId": "STU908" }
{ "_id": ObjectId("..."), "StudentId": "STU101" }

Case 1: Ascending Order

Sort StudentId in ascending alphanumeric order ?

db.alphanumericSortDemo.find({}).sort({"StudentId": 1}).collation({
    locale: "en_US", 
    numericOrdering: true
});
{ "_id": ObjectId("..."), "StudentId": "STU101" }
{ "_id": ObjectId("..."), "StudentId": "STU908" }
{ "_id": ObjectId("..."), "StudentId": "STU1010" }
{ "_id": ObjectId("..."), "StudentId": "STU1101" }
{ "_id": ObjectId("..."), "StudentId": "STU1901" }

Case 2: Descending Order

Sort StudentId in descending alphanumeric order ?

db.alphanumericSortDemo.find({}).sort({"StudentId": -1}).collation({
    locale: "en_US", 
    numericOrdering: true
});
{ "_id": ObjectId("..."), "StudentId": "STU1901" }
{ "_id": ObjectId("..."), "StudentId": "STU1101" }
{ "_id": ObjectId("..."), "StudentId": "STU1010" }
{ "_id": ObjectId("..."), "StudentId": "STU908" }
{ "_id": ObjectId("..."), "StudentId": "STU101" }

Key Points

  • numericOrdering: true treats numeric portions as numbers, not strings
  • locale: "en_US" defines the collation rules for sorting
  • Without collation, "STU1010" would come before "STU101" in lexical order

Conclusion

Use MongoDB's collation feature with numericOrdering: true to achieve proper alphanumeric sorting. This ensures numeric portions within strings are sorted numerically rather than lexically.

Updated on: 2026-03-15T00:57:57+05:30

625 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements