MongoDB and C#: Case insensitive search
The simplest and safest way to do that is using Linq
:
var names = namesCollection.AsQueryable().Where(name => name.FirstName.ToLower().Contains("hamster"));
As explained in the tutorial ToLower
, ToLowerInvariant
, ToUpper
and ToUpperInvariant
all perform matches in a case insensitive way. After that you can use all the supported string methods like Contains
or StartsWith
.
This example will generate:
{ "FirstName" : /hamster/is}
The i
option makes it case insensitive.
I've just implemented this much simpler than any of the other suggestions. However I realise due to the age of this question, this functionality may not have been available at the time.
Use the options of the Bson Regular Expression constructor to pass in case insensitivity. I just had a look at the source code and found that 'i' is all you need. For example.
var regexFilter = Regex.Escape(filter);var bsonRegex = new BsonRegularExpression(regexFilter, "i");Query.Matches("MyField", bsonRegex);
You shouldn't have to keep records twice for searching.
try to use something like this:
Query.Matches("FieldName", BsonRegularExpression.Create(new Regex(searchKey, RegexOptions.IgnoreCase)))