Home > Software engineering >  how to make a mongo filter search case insensitive in c#
how to make a mongo filter search case insensitive in c#

Time:10-28

I have this query here:

            var filter =
        builder.Eq("BuyerDetails.Buyer.Email", request.BuyerEmail)
                 | builder.Eq("BuyerDetails.Buyer.FirstName", request.FirstName)
                 & builder.Eq("BuyerDetails.Buyer.Surname", request.LastName);

however the problem is that i am unable anticipate the case of the email, firstname and surname is mongo.

if the request is firstName = "STACK" and LastName = "OVERFLOW"

and the document in mongo is "firstName = "stack" and LastName = "overflow"

it will not match.

how can i filter with and make it case insensitive?

CodePudding user response:

You need to work with the $regex operator. In MongoDB .NET Driver, refer to FilterDefinitionBuilder.Regex Method (FieldDefinition, BsonRegularExpression).

using System.Text.RegularExpressions;

builder.Regex("BuyerDetails.Buyer.FirstName", new Regex(request.FirstName, RegexOptions.IgnoreCase))

builder.Regex("BuyerDetails.Buyer.Surname", new Regex(request.LastName, RegexOptions.IgnoreCase))

Note that the above query will find the document with the field value without guarantee from start to end. Example of illustration:

Search keyword for FirstName: Stack

FirstName Is Matched?
STACK Yes
STACKxxx Yes
xxxSTACK Yes
xxxSTACKxxx Yes

If you want to filter the document with the match of the filtered string from start to end (exact match), you need the ^ start and $ end symbols in regex.

var filter =
    builder.Eq("BuyerDetails.Buyer.Email", request.BuyerEmail)
    | builder.Regex("BuyerDetails.Buyer.FirstName", new Regex($"^{request.FirstName}$", RegexOptions.IgnoreCase))
    & builder.Regex("BuyerDetails.Buyer.Surname", new Regex($"^{request.LastName}$", RegexOptions.IgnoreCase));
  • Related