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.
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With