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);
1
  • 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# Commented Aug 13, 2014 at 16:49

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

3 Comments

casing needs to be preserved, this is better that using regex because it's hitting the index right ?
@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 (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): blog.comsysto.com/2013/06/26/…. If you need a robust/fast querying or analysis of textual data I would recommend using something other than monogodb, I like elasticsearch: elasticsearch.org
I've gone with the extra field with a lower case copy, thanks
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"
}));

4 Comments

will try this thx get back to you in a bit :)
quick question is this doing a table scan or using indexes ?
This will depend on your indexes. Regex does use indexes if the Name field has an index on it.
thats what i wanted to hear, thx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.