Search code examples
c#.netmongodbmongodb-.net-drivercase-insensitive

MongoDB and C#: Case insensitive search


I am using MongoDB and the C# driver for MongoDB.

I recently discovered that all queries in MongoDB are case-sensitive. How can I make a case-insensitive search?

I found one way to do this:

Query.Matches(
    "FirstName", 
    BsonRegularExpression.Create(new Regex(searchKey,RegexOptions.IgnoreCase)));

Solution

  • 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.