Case Insensitive Sorting in MongoDB

December 2011 ยท 1 minute read

I learned, while working on an app for myself, that MongoDB always sorts case sensitive. Boo. The order of sorting is:

  1. Numerics (0-9)
  2. Upper Case Letters (A-Z)
  3. Lower Case Letters (a-z)

A few examples of the documents I have stored are:

{ title: 'iRobot', tags: [...] }
{ title: 'Rambo', tags: [...] }
{ title: 'Con Air', tags: [...] }

Running sort on the title field…

col.find().sort({ title: 1 })

yields…

  1. Con Air
  2. Rambo
  3. iRobot

This doesn’t make sense to any human and since MongoDB doesn’t have the ability to specify case insensitive sorting I needed to set up a workaround. I added a sort field and set the value to all lower case when saving my documents.

{ title: 'iRobot', stitle: 'irobot', tags: [...] }
{ title: 'Rambo', stitle: 'rambo', tags: [...] }
{ title: 'Con Air', stitle: 'con air', tags: [...] }

Now running I can run sort on the new stitle field…

col.find().sort({ stitle: 1 })

and I get the correct human sorting…

  1. Con Air
  2. iRobot
  3. Rambo

I hope that MongoDB will implement a way to do case insensitive sorting soon so extra fields aren’t needed.