11

Right now I got:

@directories = collection.directories.all.asc(:name)

But it's case-sensitive, how do I do case-insensitive sorting?

Icid
  • 1,444
  • 1
  • 12
  • 21
  • If you decide to use Ruby to do it, make sure you don't use too old a version of Rubinius. It used to do case insensitive sorting in reverse alphabetical order! https://github.com/evanphx/rubinius/issues/518 – Andrew Grimm May 05 '11 at 00:19

4 Answers4

16

Currently you cannot create case insensitive indexes in MongoDB see ...

http://jira.mongodb.org/browse/SERVER-90

So, it seems that means you cannot do case insensitive "sorting" either.

You can upvote the feature for future inclusion in MongoDB via the link above if you find it useful.

Eliot Horowitz from 10Gen (the supporters of MongoDB) suggest this in the meantime:

For short term - I would just add a 2nd field that you call .toLower() on before inserting. Then you can sort on that.

Justin Jenkins
  • 26,590
  • 6
  • 68
  • 1,285
4

You will probably have to store the field twice, once with its real value, and again in all lowercase. You can then query the lowercased version for case-insensitive search (don't forget to also lowercase the query string).

This approach works (or is necessary) for many database systems, and it should perform better than regular expression based techniques (at least for prefix or exact matching).

Check this answer

Community
  • 1
  • 1
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
2

If your collection is not going to crash memory (99% of the time), just sort it there:

Blah.all.sort_by{|i| i.blah_field.downcase}
Peter Hawkins
  • 373
  • 4
  • 7
-4
regexsearch = Regexp.new(params[:search], true)

@users = User.where(:email => regexsearch).all

That should do it :)

Marek
  • 49,472
  • 15
  • 99
  • 121
DrewBaumann
  • 308
  • 2
  • 10