Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make case-insensitive queries on Mongodb?

var thename = 'Andrew'; db.collection.find({'name':thename}); 

How do I query case insensitive? I want to find result even if "andrew";

like image 285
user847495 Avatar asked Aug 18 '11 02:08

user847495


People also ask

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.

Are MongoDB keys case-sensitive?

Mongodb supports case insensitive indexing now.

How would you make a case insensitive query in mysql?

select * from users where lower(first_name) = 'ajay'; The method is to make the field you are searching as uppercase or lowercase then also make the search string uppercase or lowercase as per the SQL function.

How do I query in MongoDB?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.


2 Answers

Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^, which anchors the regular expression to the start of the string), and those using the i flag for case insensitivity will not use indexes, even if they exist.

An alternative option you might consider is to denormalize your data to store a lower-case version of the name field, for instance as name_lower. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:

db.collection.find({"name_lower": thename.toLowerCase()}) 

Or with a prefix match (a rooted regular expression) as:

db.collection.find( {"name_lower":     { $regex: new RegExp("^" + thename.toLowerCase(), "i") } } ); 

Both of these queries will use an index on name_lower.

like image 138
dcrosta Avatar answered Sep 23 '22 05:09

dcrosta


You'd need to use a case-insensitive regular expression for this one, e.g.

db.collection.find( { "name" : { $regex : /Andrew/i } } ); 

To use the regex pattern from your thename variable, construct a new RegExp object:

var thename = "Andrew"; db.collection.find( { "name" : { $regex : new RegExp(thename, "i") } } ); 

Update: For exact match, you should use the regex "name": /^Andrew$/i. Thanks to Yannick L.

like image 29
Chris Fulstow Avatar answered Sep 21 '22 05:09

Chris Fulstow