Reputation: 7316
The question "how can I do a case insensitive find in mongo" seems to be mostly answered along the lines of "use a regex". This is fine if your search string is known in advance (/foo/
), or is known not to contain regex operators (^.+*$/\-()[]
...).
In my case, I want to do a case insensitive search on email addresses, which can contain dots and plusses. "Regex escaping" the string is certainly possible, but even if there was a standard "Regex.escapeString
" function (which there isn't), it's already starting to feel difficult to explain and maintain for such a simple problem.
Is there a way to do a case insensitive match in mongo without using regex?
Upvotes: 5
Views: 1679
Reputation: 5029
You can use the Case Insensitive Indexes:
db.users.createIndex(
{ type: 1 },
{ collation: { locale: 'en', strength: 2 } }
)
and query for users as follows:
db.users.find(
{ email: "[email protected]" }
).collation(
{ locale: 'en', strength: 2 }
)
...will give you results:
The strength
parameter is the level of comparison to perform. Corresponds to ICU Comparison Levels.
Upvotes: 0
Reputation: 20304
You can use aggregate()
to do it, instead of find()
with $regex
:
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{ "$toLower": "$email" },
{ "$toLower": "[email protected]" }
]
}
}
}
])
Upvotes: 2