Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive sorting in MongoDB

How can I sort a MongoDB collection by a given field, case-insensitively? By default, I get A-Z before a-z.

like image 416
Varun Kumar Avatar asked Apr 08 '14 08:04

Varun Kumar


People also ask

How do I sort a case insensitive in MongoDB?

This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.

Is MongoDB data case-sensitive?

As mentioned by @natac13 and @007_jb mongo shell is an interactive javascript interpreter and hence it is also case-sensitive.

Does MongoDB support sorting?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted.

What sorting algorithm does MongoDB use?

If MongoDB cannot obtain the sort order via an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first k results (or last, depending on the sort order) seen so far by the underlying index or collection access.


2 Answers

Update: As of now mongodb have case insensitive indexes:

Users.find({})   .collation({locale: "en" })   .sort({name: 1})   .exec()   .then(...) 

shell:

db.getCollection('users')   .find({})   .collation({'locale':'en'})   .sort({'firstName':1}) 

Update: This answer is out of date, 3.4 will have case insensitive indexes. Look to the JIRA for more information https://jira.mongodb.org/browse/SERVER-90


Unfortunately MongoDB does not yet have case insensitive indexes: https://jira.mongodb.org/browse/SERVER-90 and the task has been pushed back.

This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.

like image 124
Sammaye Avatar answered Sep 22 '22 18:09

Sammaye


Sorting does work like that in MongoDB but you can do this on the fly with aggregate:

Take the following data:

{ "field" : "BBB" } { "field" : "aaa" } { "field" : "AAA" } 

So with the following statement:

db.collection.aggregate([     { "$project": {        "field": 1,        "insensitive": { "$toLower": "$field" }     }},     { "$sort": { "insensitive": 1 } } ]) 

Would produce results like:

{     "field" : "aaa",     "insensitive" : "aaa" }, {     "field" : "AAA",     "insensitive" : "aaa" }, {     "field" : "BBB",     "insensitive" : "bbb" } 

The actual order of insertion would be maintained for any values resulting in the same key when converted.

like image 36
Neil Lunn Avatar answered Sep 21 '22 18:09

Neil Lunn