Case Insensitive Sorting with Mongoose and MongoDB

Sorting in MongoDB can cause a lot pain (in the ass!). The problem: MongoDB always sorts case sensitive in the following order

  1. Numerics: 0-9
  2. Uppercase letters: A-Z
  3. Lowercase letters: a-z

For the following examples, assume the upcoming Tag schema and documents in our Tags collection:

Schema

{
   name: String,
   approved: boolean,
   …
}

Documents in Collection

{name: 'Cape Canaveral', approved: 0, …},
{name: 'beer', approved: 1, …},
{name: 'Tour de France', approved: 1, …},

Sort in MongoDB

Actually, there is no difference sorting documents in MongoDB whether using Mongoose or any other MongoDB driver. The previous mentioned Tags collection is based on the Tag schema with respective fields. The native sorting result using Mongoose and the Tag schema will look like this:

Sort Query

Tag.find({}).sort('name').exec(function(err, tags) {…});  

Sorting result

  1. Cape Canaveral
  2. Tour de France
  3. beer

You see, we actually expect beer to be the first result, but it isn't.

Add real sorting

The sorting result above doesn't make sense to humans and we expect the platform to return results sorted by ignoring lower- or uppercase. This insensitive sorting isn't integrated in MongoDB. We need to add a workaround by adding a new field to the schema. In our case, we add a normalized field to the Tag schema. This field contains the name in lowercase.

{
    name: String,
    normalized: String,
    approved: boolean,
    …
}

The documents in the Tags collection change to

{name: 'Cape Canaveral', normalized: 'cape canaveral', approved: 0, …},
{name: 'beer', normalized: 'beer', approved: 1, …},
{name: 'Tour de France', normalized: 'tour de france', approved: 1, …},

Now we run the sorting on normalized instead of name and get the expected result.

Sort Query

Tag.find({}).sort('normalized').exec(function(err, tags) {…});  

Sorting result

  1. beer
  2. Cape Canaveral
  3. Tour de France

Native MongoDB functionality

Since 2009 there is an open issue in the MongoDB Jira, but still unresolved. We'll see if the Mongo team implements this feature in the future. However, you can use the presented workaround to get the functionality needed. Even though you blow up the database by adding doubled fields to collections.

Explore the Library

Find interesting tutorials and solutions for your problems.