c# mongodb case sensitive search

狂风中的少年 提交于 2019-12-04 21:29:28

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.Text(email), 
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

I'd prefer using Linq.

var match = theCollection.AsQueryable().SingleOrDefault(x =>
    x.Email.ToLower() == emailToSearchFor.ToLower());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!