Can MongoDB do alphanumeric sortings?

I need to do alphanumeric sorting in one of the fields in my collection. This field contains chromosome information.

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 it was interesting whether MongoDB has a built-in solution for this kind, or should we crack it, as we usually do in Oracle. If there is no built-in solution, what is the best way to get this view? Natural sorting is an acceptable solution, but I have already applied it to another field.

Any help would be greatly appreciated.

+8
source share
2 answers

MongoDB does not have a built-in way to sort alphanumerical data. But when all your data has a field with a string with the same convention "Chr" + number, you can put the number in another field, save it as an integer, not a string, and sort by this value.

+5
source

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

Mongo provides sorting options for alphanumeric sorting.

Example:-

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

0
source

All Articles