0

How do I make this case insensitive? At the moment it works but only when the case matches.

var query =  Query.Matches("Name", searchString);
psoshmo
  • 1,490
  • 10
  • 19
fuzzybear
  • 2,325
  • 3
  • 23
  • 45
  • The question does not talk about the match operator neither does it provide example in c# thus the question is duplicate but not with c# – fuzzybear Aug 13 '14 at 16:49

2 Answers2

2

You can store the names in all uppercase or lowercase, and convert your search query to the correct case. If you would like to persist the original casing, you can create an additional field for searching, in an all upper/lower case. Then convert your query to all upper/lower case, and query on the upper/lower case version of the field. This would perform much better than using a regex.

For example:

var query = Query.Matches("Name_Upper", searchString.ToUpper());
wbennett
  • 2,545
  • 21
  • 12
  • casing needs to be preserved, this is better that using regex because it's hitting the index right ? – fuzzybear Aug 13 '14 at 16:37
  • @saj If you use a case insensitive regex, even on an index, it will not perform optimally, because it will need to scan the index. If you use text indices with a text match (http://docs.mongodb.org/manual/core/index-text/) you should be alright. Checkout this writeup on the difference (the graph on the bottom explicitly points out the diff): http://blog.comsysto.com/2013/06/26/mongo-fulltext-search-vs-regular-expressions/. If you need a robust/fast querying or analysis of textual data I would recommend using something other than monogodb, I like elasticsearch: http://www.elasticsearch.org/ – wbennett Aug 13 '14 at 17:16
  • I've gone with the extra field with a lower case copy, thanks – fuzzybear Aug 13 '14 at 20:05
1

You can do this using regexes. The Mongo query would look like this:

find({"Name": {"$regex": searchString, "$options": "i"}})

In C# you would write it something like this:

Query.Matches("Name", new BsonDocument(new Dictionary<string, object> {
    "$regex": searchString,
    "$options": "i"
}));
robbrit
  • 17,560
  • 4
  • 48
  • 68