2

Using regex = { name : { $regex : inputName, $options: 'i' } }

even when input name is blank, the query returns the first document. Even when input is a, query returns the first document which have a anywhere in the name.

I want if then input name is "jo", then it should only return the first document either with name "Jo", "JO", "jO", "jo".

Please remember i recieve inputName as variable

codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • @WiktorStribiżew this does not work. – codeofnode Aug 10 '16 at 12:35
  • Yeah, I updated my answer after double checking. – Wiktor Stribiżew Aug 10 '16 at 12:38
  • @WiktorStribiżew sorry for my previous comment i checked with some syntax error. Now your answer works good. – codeofnode Aug 10 '16 at 12:44
  • The question is not about how to make a search case insensitive, but how to perform an exact search. Thus, [*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) is not the *exact duplicate* of this one. – Wiktor Stribiżew Aug 11 '16 at 06:35

1 Answers1

2

Use a JS RegExp constructor to build a regexp dynamically:

new RegExp("^" + inputName + "$", "i")

The i modifier will provide case insensitive matching and ^ / $ anchors will make sure the full string match will be requried.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563