Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do alphanumeric sort in mongoDB?

I have a collection like this.

{"userID" : "TR31"}
{"userID" : "TR1059"}
{"userID" : "TR1043"}

I want to sort this document in an ascending or descending order, I tried this way db.col.find({}).sort({"userID" : 1}) and db.col.find({}).sort({"userID" : -1}) but no luck.

Expected Result:

    {"userID" : "TR31"}
    {"userID" : "TR1043"}
    {"userID" : "TR1059"}

Please advise. Thanks in advance.

like image 755
Senthur Deva Avatar asked Aug 21 '18 13:08

Senthur Deva


1 Answers

Use collation with numericOrdering set to true in 3.4.

Something like

db.col.find({}).sort({"userID" : 1}).collation( { locale: "en_US", numericOrdering: true });
like image 145
s7vr Avatar answered Oct 21 '22 05:10

s7vr