How to do alphanumeric sort in MongoDB?



You need to set numericOrdering: true for alphanumeric sort. Let us first create a collection with documents −

> db.alphanumericSortDemo.insertOne({"StudentId":"STU1010"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ccf149adceb9a92e6aa194c") } > db.alphanumericSortDemo.insertOne({"StudentId":"STU1101"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ccf14a2dceb9a92e6aa194d") } > db.alphanumericSortDemo.insertOne({"StudentId":"STU1901"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ccf14a9dceb9a92e6aa194e") } > db.alphanumericSortDemo.insertOne({"StudentId":"STU908"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ccf14aedceb9a92e6aa194f") } > db.alphanumericSortDemo.insertOne({"StudentId":"STU101"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ccf14b2dceb9a92e6aa1950") }

Following is the query to display all documents from a collection with the help of find() method −

> db.alphanumericSortDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" } { "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" } { "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" } { "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" } { "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" }

Case 1 − When you want the result in ascending order.

Here is the query to do alphanumeric sort in MongoDB −

> db.alphanumericSortDemo.find({}).sort({"StudentId" : 1}).collation( { locale: "en_US", numericOrdering: true });

This will produce the following output −

{ "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" } { "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" } { "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" } { "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" } { "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" }

Case 2 − When you want the result in descending order.

Here is the query to do alphanumeric sort in MongoDB −

> db.alphanumericSortDemo.find({}).sort({"StudentId" : -1}).collation( { locale: "en_US", numericOrdering: true });

This will produce the following output −

{ "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" } { "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" } { "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" } { "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" } { "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" }
Updated on: 2019-07-30T22:30:26+05:30

583 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements