How to do alphanumeric sort in mongoDB?

只愿长相守 提交于 2019-12-19 18:55:31

问题


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.


回答1:


Use collation with numericOrdering set to true in 3.4.

Something like

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



回答2:


One approach is, you need to save using a prefix.

{"userID" : "TR0031"},
{"userID" : "TR1059"},
{"userID" : "TR1043"}

so that you can achieve as you expect.

{"userID" : "TR0031"},
{"userID" : "TR1043"},
{"userID" : "TR1059"}


来源:https://stackoverflow.com/questions/51950323/how-to-do-alphanumeric-sort-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!