Ori Refael Ori Refael - 6 months ago 61
C# Question

c# mongodb case sensitive search

I have a collection in which I store Email and password of user.

I obviously don't want to require the user to insert his email case sensitive and to be exactly as when he first registered.

I'm using mongodb 2.0 c# driver, I'm repeating it because I saw solutions to queries written with regex but I'm afraid I cant user it in here.

my query looks like

var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Eq(u => u.Email, email),
Builders<ME_User>.Filter.Eq(u => u.Password, password));
ME_User foundUser = null;
var options = new FindOptions<ME_User>
Limit = 1
using (var cursor = await manager.User.FindAsync(filter, options))
while (await cursor.MoveNextAsync())
var batch = cursor.Current;
foreach (ME_User user in batch)
foundUser = user;

I have an issue with disorder, kill me, but I cant allow myself save this data again with lower case and have 2 copies of the same thing. Also, I want the email to be saved EXACTLY like the user inserted it.


Filtering on string fields in Mongodb is case sensitive without using regular expressions. Why exactly you cannot use regular expressions?

Your query can be edited like this:

var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Regex(u => u.Email, new BsonRegularExpression("/^" + email + "$/i"), 
Builders<ME_User>.Filter.Eq(u => u.Password, password));

Notice the "^" and "$" signs to specify a complete word search and most important the case-insensitive operator at the end of the regular expression ("/i").

Another way vould be the Text search, that requires the creation of a text index and is case insensitive for latin alphabet: http://docs.mongodb.org/manual/reference/operator/query/text/#match-operation

In C#, you will use with the Text Filter:

var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Eq(u => u.Password, password));

With a text index query in an OR clause, you will need to create an index on Password field as well, otherwise the OR query will produce an error:

Other non-TEXT clauses under OR have to be indexed as well