1

My following find query don't work in lowercase scenario. If the value in collection is capital & which i pass is in lowercase gives no result.

How to override case sensitive behavior?

User.find({
        $or:
        [
            { 'basicinformation.firstname': { '$regex': firstname + '.*' } },
            { 'basicinformation.lastname': { '$regex': lastname + '.*' } }
        ]
    }
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Anup
  • 9,396
  • 16
  • 74
  • 138
  • possible duplicate of [MongoDB: Is it possible to make a case-insensitive query?](http://stackoverflow.com/questions/1863399/mongodb-is-it-possible-to-make-a-case-insensitive-query) – WiredPrairie May 23 '14 at 10:44
  • I seen that question...the answer don't match my requirement..! – Anup May 23 '14 at 11:06
  • In fact, it has the answer repeated several times with the proper warnings that it's a performance issue to use a case insensitive search in MongoDB. `/i` is ignore case. – WiredPrairie May 23 '14 at 14:12

1 Answers1

2

Add $options to your $regex operator:

User.find({
    $or:
    [
        { 
            'basicinformation.firstname': { 
                '$regex': firstname + '.*', '$options': 'i' 
             }
        },
        { 
            'basicinformation.lastname': { 
                '$regex': lastname + '.*', '$options': 'i'  
            }
        }
    ]
}

So the "i" there makes the search case insensitive. Note that invoking a case insensitive search is going to force an index scan at best, even if you anchor ^ your regex to the start of the string.

Since this could well impact your performance, consider other options such as a text search index and query or modifying the case with either additional fields or within your input and store in a single case format if you can get away with that.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • I have 1 more issue....If User types `a` & searches for it.....He should get results whose first name starts from `a`....but in my current query it checks the complete name & if there is `a` it displays them all. – Anup May 23 '14 at 08:50
  • @Anup you use the anchoring caret or `^` character at the start of your regex to match from the beginning of the string. I already commented on that with further information while you were posting comments. – Neil Lunn May 23 '14 at 08:51
  • Please open up a new question next time. One question, multiple answers per topic – Markus W Mahlberg May 23 '14 at 11:01