Mongo C driver - Building filter dynamically with nesting
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When a MongoDB query depends on optional user input, the clean approach is to build small filter fragments and combine them at the end. With the MongoDB C# driver, that usually means collecting FilterDefinition objects and nesting them with And and Or only where the logic actually requires it.
Start With the Filter Builder
The C# driver exposes a fluent API through Builders<T>.Filter. That builder creates strongly typed query fragments without forcing you to concatenate raw BSON strings.
Suppose you have this model:
Now imagine a search screen where status, minimum total, and a free-text customer filter are all optional.
Build Filters Incrementally
A good pattern is to add only the filters that are actually requested:
This is dynamic, type-safe, and easy to extend.
Add Nesting Only for Real Logic Groups
Nested filters become necessary when the logic is not just a flat AND. For example, “active or pending orders, and not deleted” should be grouped explicitly.
The important point is structure. Create subgroups as variables when the logic has real parentheses. That makes the final query readable and avoids mistakes when conditions grow.
Why This Pattern Scales Better Than Raw BSON
You can build equivalent queries with BsonDocument, but strongly typed filters catch property-name mistakes at compile time and refactor more safely. If CustomerName is renamed, the lambda-based filter breaks at compile time instead of silently producing a bad query.
That matters once dynamic filtering starts to grow across multiple screens or API endpoints.
Debugging the Generated Query
When filters become complicated, it helps to render the generated BSON during debugging so you can verify the logical shape.
This is especially useful when a dynamic Or group is being combined with several And conditions and you want to confirm the nesting is correct.
Common Pitfalls
A common mistake is calling And or Or too early and then trying to mutate the combined filter later. It is usually easier to collect small filters first and combine them once.
Another mistake is building regex filters directly from raw user input without considering escaping and performance. Dynamic does not mean unbounded.
A third mistake is using string field names everywhere when a typed model is available. Strongly typed expressions are more maintainable.
Summary
- Build dynamic MongoDB filters by collecting small
FilterDefinitionfragments. - Use
Builders<T>.Filterand strongly typed expressions whenever possible. - Introduce nested
AndandOrgroups only when the query logic truly needs grouping. - Render the final BSON while debugging to confirm the generated structure.
- Keep regex and user-driven filter logic controlled so the query stays correct and maintainable.

