Example:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
Example:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
If you need to create the regexp from a variable, this is a much better way to do it: https://stackoverflow.com/a/10728069/309514
You can then do something like:
This has the benefit be being more programmatic or you can get a performance boost by compiling it ahead of time if you're reusing it a lot.
One very important thing to keep in mind when using a Regex based query - When you are doing this for a login system, escape every single character you are searching for, and don't forget the ^ and $ operators. Lodash has a nice function for this, should you be using it already:
Why? Imagine a user entering
.*
as his username. That would match all usernames, enabling a login by just guessing any user's password.I had faced a similar issue and this is what worked for me:
TL;DR
Correct way to do this in mongo
Do not Use RegExp
Go natural And use mongodb's inbuilt indexing , search
Step 1 :
Step 2 :
Need to create index on whichever TEXT field you want to search , without indexing query will be extremely slow
step 3 :
Using a filter works for me in C#.
It may even use the index because I believe the methods are called after the return happens but I haven't tested this out yet.
This also avoids a problem of
that mongodb will think p.Title.ToLower() is a property and won't map properly.