1

In my user authentication I allow users to enter case insensitive email. Recently I saw in the logs that one user can not authenticate himself. Reason is because his email address has + character inside, and for some reason MongoDB case insensitive search can not find email with special characters. It's like the special characters are ignored when performing the regex search.

I created this testing example: Mongo Playground

What is the reason of this behavior and how to solve this?

NeNaD
  • 18,172
  • 8
  • 47
  • 89

3 Answers3

0

I solved it without $regex, with aggregate:

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          { "$toLower": "$email" },
          { "$toLower": "EXAMPLE+@gmail.com" }
        ]
      }
    }
  }
])

Working Example

Yet, if someone have solution with $regex, I would like to see that.

NeNaD
  • 18,172
  • 8
  • 47
  • 89
0

If your users email have regex special characters like +,.,(,[ etc
You can escape them before searching else MongoDB will think you mean the regex special character

Javascript code (from this answer)

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 
}

With the above function + would become \\+ and you could search like this

I am not sure i understanded but i think you need this.

Takis
  • 8,314
  • 2
  • 14
  • 25
0

I think you can simply do a "double"-escape:

db.collection.find({
  email: {
    "$regex": "Example\\+?@gmail.com",
    "$options": "i"
  }
})

Applied to your example it will now match both entries: https://mongoplayground.net/p/7LMSCtjB-k7

eol
  • 23,236
  • 5
  • 46
  • 64