Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make a mongo filter search case insensitive in c#

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading