Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

[ { 
    title: 'unnamed-1',
    text: '<p>sdaasdasdasd</p>',
    tags: [],
    _id: 'Wkxxpapm8bbiq59ig',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' },
{ 
    title: 'unnamed-10',
    text: '',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public',
    _id: 'aDSN2XFjQPh9HPu4c' },
{ 
    title: 'unnamed-2',
    text: '<p>kkhjk</p>',
    tags: [],
    _id: 'iM9FMCsyzehQvYGKj',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' },
{ 
    title: 'unnamed-3',
    text: '',
    tags: [],
    _id: 'zK2w9MEQGnwsm3Cqh',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' }]

The problem is that it seems to sort on the first numeric character so it thinks the proper sequence is 1, 10, 2, 3, etc.... what I really want is for it to sort on both the whole numerical part so that 10 would be at the end.

I'd prefer not to do this by having additional numbers such as 01 or 001 for the numbers.

How would I do that?

like image 942
funkyeah Avatar asked Apr 20 '13 23:04

funkyeah


2 Answers

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.

like image 162
Eugene Kaurov Avatar answered Oct 01 '22 08:10

Eugene Kaurov


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.

like image 33
Leopd Avatar answered Oct 01 '22 06:10

Leopd