Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case-insensitive query on mongodb

Tags:

mongodb

is there a way to query for a case-insensitive value on mongo without using map/reduce?

like image 952
w43L Avatar asked Mar 31 '11 11:03

w43L


People also ask

How do you write a case insensitive query in MongoDB?

The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.

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.

What is $NOT operator in MongoDB?

Definition. $not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .


2 Answers

Suppose you have document that contains tag field and you want search on it

Tags
{
  tag,
  ...
 }

First option is use regex(but it work slow as @RestRisiko said):

db.tags.find( { "tag" : { "$regex" : "C#", "$options" : "-i" } })

Second option is create another, lower case field( and in mongodb it best way):

Tags
{
  tag,
  tagLower,
  ..
}

And use find as usual:

db.tags.find( { "tagLower" : "c#"})

It will work faster, because above code can use index for search.

like image 89
Andrew Orsich Avatar answered Oct 09 '22 10:10

Andrew Orsich


You have to normalize the data to be queried. Using a regular expression for case-insensitive search might work as well it won't use indexes. So your only option is to normalize. If you need to preserve the original state then you need to denormalize the data and store the normalized values in a dedicated column of the document.

like image 39
Andreas Jung Avatar answered Oct 09 '22 08:10

Andreas Jung