Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MongoDB do alphanumeric sort?

Tags:

mongodb

I need to do a alphanumeric sort on one of the fields in my collection. This field contains Chromosome info.

Chr1, 
Chr2,
..,
..,
..,
Chr10,
Chr11,
..,
..,
ChrX,
ChrY

Instead of getting the values in this order, I get them in

Chr1, 
Chr11

This is a common problem and was wondering whether MongoDB has an in-built solution for this sort or should we hack it as we normally do in Oracle. If there is no in-built solution, what is the best way to get this sort? Natural sort is an acceptable solution, but I have already applied it to another field.

Any help would would be greatly appreciated.

like image 461
Arun J Avatar asked May 26 '13 15:05

Arun J


Video Answer


2 Answers

MongoDB has no build-in way of sorting data alphanumerical. But when all of your data has a field with a string with the same convention of "Chr" + number, you could put the number into a different field, keep it as an integer instead of a string, and sort by that.

like image 84
Philipp Avatar answered Oct 11 '22 13:10

Philipp


Please refer to "https://docs.mongodb.com/manual/reference/collation".

Mongo provides collation for alphanumeric sorting.

Example:-

db.names.find({}).sort({username:1}).collation({locale:'en_US', numericOrdering:true})

like image 32
Laxman Singh Garia Avatar answered Oct 11 '22 12:10

Laxman Singh Garia