Divyesh Savaliya
Divyesh Savaliya

Reputation: 2730

Mongodb regex not matching exact when . (dot) in search

I want to check if email already registered in my MongoDB database or not.
I have one user registered with [email protected]
But If I check for [email protected] it still matches record of [email protected]
I tried following queries

db.getCollection('users').find(
     {"email":{ $regex: new RegExp([email protected], "i") } 
})

db.getCollection('users').find(
         {"email":{ $regex: new RegExp(/[email protected]/, "i") } 
})

db.getCollection('users').find(
         {"email":{ $regex: new RegExp(/^([email protected])$/, "i") } 
})

db.getCollection('users').find(
         {"email":{ $regex: new RegExp(/^(test.23@test\.com)$/, "i") } 
})

How can I search exact match with case insensitive?

Upvotes: 0

Views: 959

Answers (1)

Alex Blex
Alex Blex

Reputation: 37038

You don't need to do regex. Mongodb support collations since v3.4

db.getCollection('users').find(
     {"email":"[email protected]"} 
).collation(
     {locale:"en", strength: 1}
)

will match "[email protected]", "[email protected]" and anything in between.

As a side note passing user's input straight to the regex query you risk to lose your server one day. Read for inspiration https://www.rexegg.com/regex-explosive-quantifiers.html If you decide to proceed with regex approach you can escape dots at the time when you escape parenthesis, brackets, escape character and other special symbols from regex syntax.

Upvotes: 1

Related Questions