Arun J
Arun J

Reputation: 557

Can MongoDB do alphanumeric sort?

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.

Upvotes: 9

Views: 1997

Answers (3)

Dev
Dev

Reputation: 57

You can also use if you are using aggregation in mongodb:-

db.names.aggregate([...query, {$sort:{username:1}]).collation({locale:'en_US', numericOrdering:true});

Don't forget to add sorting of key in query array otherwise you will not get sorting order.

This thing is not available in documentation.

Upvotes: 0

Laxman Singh Garia
Laxman Singh Garia

Reputation: 73

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})

Upvotes: 1

Philipp
Philipp

Reputation: 69663

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.

Upvotes: 5

Related Questions