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
Selected Reading
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: truetreats 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.
Advertisements
