Search code examples
c#mongodbmongodb-.net-driver

MongoDB C# Query to filter fields omitting non-digits while filtering


I have documents in MongoDB with 'SSN' string field. It could contain only digits or digits with hyphens, for ex.:

"123456789"

"12-345-6789"

"123-456789"

The incoming filter parameter could come only as digits, for ex. "123456789", "187641287" and so on. How to build filter query to find those records? I mean the non-digits characters in 'SSN' should be ignored and only digits should be compared with filter parameter.

I looked at Builders.Filter.Where but it looks like it will not work because it accepts Expression:

ssn ('123454784') // filter ssn value coming outside

Func<MyDocument, bool> ssnExpression() => doc =>
{
    var ssnOnlyDigits = doc.SSN ?? null;
    ssnOnlyDigits = string.IsNullOrEmpty(ssnOnlyDigits) ? null : Regex.Replace(ssnOnlyDigits, @"\D", string.Empty);
    return ssnOnlyDigits != null && ssnOnlyDigits.Equals(ssn);
};

return Builders<MyDocument>.Filter.Where(ssnExpression());

Any advice will be appreciated.

P.S. I cannot store 'SSN' with only digits into DB.


Solution

  • As @aneroid suggested this could be done with Regex. In C#, the code looks like the following:

    ssnValue // ssn filter value coming from outside
    var regex = new BsonRegularExpression("^" + string.Join("-?", ssnValue.ToCharArray()) + "$");
    var filter = Builders<MyDocument>.Filter.Regex(selector, regex);