Skip to content Skip to sidebar Skip to footer

How To Make A Mongodb Query Sort On Strings With -number Postfix?

I have a query: ownUnnamedPages = Entries.find( { author : this.userId, title : {$regex: /^unnamed-/ }}, {sort: { title: 1 }}).fetch() That returns the following array sorted: [ {

Solution 1:

You can use

db.collectionName.find().sort({title: 1}).collation({locale: "en_US", numericOrdering: true})

numericOrdering flag is boolean and is Optional. Flag that determines whether to compare numeric strings as numbers or as strings. If true, compare as numbers; i.e. "10" is greater than "2". If false, compare as strings; i.e. "10" is less than "2". Default is false.

Solution 2:

MongoDB can't sort by numbers stored as strings. You either have to store the number as an integer in its own field, pad with leading zeroes, or sort the results after they've been returned from the database.

Solution 3:

If you 0 pad the numbers you will be able to search as a string in the right order, so instead of 0,1,2,3,4,5,6,7,8,9,10,11... use 01,02,03,04,05,06,07,08,09,10,11... and a string search will return them in order.

Solution 4:

The mongo documentation said you can use Collation for this goal as @Eugene Kaurov said you can use

.collation({locale: "en_US", numericOrdering: true})

this is the official documentation: mongo ref

and be aware that the accepted answer is not correct now

Solution 5:

In mongo is not possible (sort strings in ascii) but you can sort with the below function after you get all documents from the collection

constsortString = (a, b) => {
  constAA = a.title.split('-');
  constBB = b.title.split('-');

  if (parseInt(AA[1], 10) === parseInt(BB[1], 10)) {
    return0;
  }
  return (parseInt(AA[1], 10) < parseInt(BB[1], 10)) ? -1 : 1;
};

document.sort(sortString);

Post a Comment for "How To Make A Mongodb Query Sort On Strings With -number Postfix?"