How to Make a Case InSensitive filter in Nin (Not in) Clause in C# using MongoDB Driver FilterDefinition
Loading
How to Make a Case InSensitive filter in Nin (Not in) Clause in C# using MongoDB Driver FilterDefinition
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Aravind GovindarajRank #430 · 5.8K reputationPosted Jan 5, 2023, 11:42 AM EST
Could you please check will this helps
Sagar MaldeRank #2,097 · 684 reputationPosted Jan 6, 2023, 12:20 AM EST
Hi Aravind,
Thanks for the reply, but heres the existing code which I am using to filter the records and want to use Nin inside this only.
List ChargesToIgnore = new List {}; // Some Array that needs to ignored on filter var Filter = Builders.Filter.And(Builders.Filter.Where(x => x.CountryId == request.CountryId), Builders.Filter.Where(x => x.FFr == request.ForeignRun || x.FFr == "F & C"), Builders.Filter.Lte("EffectiveFrom", DateTime.UtcNow), Builders.Filter.Gte("EffectiveTo", DateTime.UtcNow), Builders.Filter.Where(x => x.Port == request.PortId), Builders.Filter.Where(x => x.Vessels.Any(z => z.ToLower() == request.TypeOfShip.ToLower())), Builders.Filter.Nin(x => x.ChargeName, ChargesToIgnore));Can you please suggest the Nin case insensitive logic inside this?
Aravind GovindarajRank #430 · 5.8K reputationPosted Jan 6, 2023, 4:49 AM EST
could you please check is this extension helps you
https://stackoverflow.com/questions/25745276/mongodb-c-sharp-driver-case-insensitive-compare-using-in-or-contains-on-a-listSagar MaldeRank #2,097 · 684 reputationPosted Jan 6, 2023, 5:18 AM EST
Unfortunately its not working for Nin clause
Sagar MaldeRank #2,097 · 684 reputationPosted Jan 7, 2023, 12:40 AM EST
Found the Solution... I modified the In Clause extension as below and is working for me.
public static FilterDefinition Nin( this FilterDefinitionBuilder builder, Expression> expr, IEnumerable values, bool ignoreCase) { if (!ignoreCase) { return builder.Nin(expr, values); } var filters = values .Select(v => !builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i"))); return builder.And(filters); }Thanks.