MongoDB Filtering in C# - Beginner's Guide For Easy Filters

I am making more of an effort to familiarize myself with document databases in my side projects, and MongoDB is currently my go-to. In fact, I recently wrote about inserting data to MongoDB in C# and wanted to follow up with this article's topic: MongoDB filtering in C#. Filtering is important when it comes to MongoDB, not only to be able to query for records... but because when you want to run a delete or an update, you also need to filter properly!

This article focuses on beginner concepts when it comes to working with MongoDB filters. You'll see simplified code examples demonstrating how to construct filters so when it's time to query, delete, or update you'll be all set.


What's In This Article: MongoDB Filtering in C#

Remember to check out these platforms:

// FIXME: social media icons coming back soon!


MongoDB Filtering in C# Using FilterDefinitionBuilders

When working with MongoDB in C#, one powerful tool for filtering documents is the MongoDB FilterDefinitionBuilder. The FilterDefinitionBuilder allow us to construct filter expressions easily and efficiently, making the process of querying MongoDB much simpler.

I personally like to start off by getting an instance of the FilterDefinitionBuilder and then creating the FilterDefinition directly from that. However, if I plan on building more complex rules out for filtering, I'll generally start with the FilterDefinitionBuilder instance and an instance of an empty FilterDefinition.

Here's an example of how to use the MongoDB FilterDefinitionBuilder to filter documents in MongoDB using C#:

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Eq("field", "value");
var results = collection.Find(filter).ToList();

In the code above, we get the FilterDefinitionBuilder instance assigned to a variable for use. This assignment is technically unnecessary, but I find it helps clean code up if I need to ask for the FilterDefinitionBuilder instance multiple times. From there, we're using an "eq" filter for an equality filter on a field called "field" and a string value of "value". Not very creative, but gets the job done!

If you want to follow along with the content in this article, you can check out this video on filtering data in MongoDB using C#:


MongoDB's Comparison Operators

In order to get up to speed with filtering in MongoDB, we need to understand the comparison operators. These operators allow you to compare specific field values with other values or expressions. Some commonly used comparison operators include:

  • $eq: Matches values that are equal to a specified value.
  • $ne: Matches values that are not equal to a specified value.
  • $gt: Matches values that are greater than a specified value.
  • $lt: Matches values that are less than a specified value.

The FilterDefinitionBuilder has access to methods that map to these operators. Consider the following example where we want to retrieve all documents from a MongoDB collection where the age is greater than or equal to 18:

var ageFilter = Builders<Person>.Filter.Gte(x => x.Age, 18);
var filteredDocuments = collection.Find(ageFilter).ToList();

In this example, we use the $gte comparison operator (which stands for "greater than or equal to") to filter documents where the age field is greater than or equal to 18. We use the Builders<Person> static class, with a type parameter for the type of our entity, so that we can see the properties when we build the filter expression. If we use BsonDocument as the type, we need to provide the property name in a string:

var ageFilter = Builders<BsonDocument>.Filter.Gte("Age", 18);
var filteredDocuments = collection.Find(ageFilter).ToList();

Range Queries and Pattern Matching in MongoDB

MongoDB also provides operators that enable you to perform range queries and pattern matching. Two commonly used operators for these purposes are:

  • $in: Matches any of the specified values in an array.
  • $regex: Matches documents based on a specified pattern using regular expressions.

These operators are particularly useful when you want to filter documents based on a range of values or apply pattern-based filters. Now let's check out an example that demonstrates how to perform a range query using the $in operator:

var rangeFilter = Builders<Person>.Filter.In(x => x.Age, new[] { 18, 19, 20 });
var filteredDocuments = collection.Find(rangeFilter).ToList();

Like before, we use the Builders<Person> static class. Here, we utilize the $in operator to filter documents where the age field matches any of the specified values in the given array.


Combining Filters for MongoDB in C#

Now that we've seen how to create some basic MongoDB filters in C#, which are based on the comparison operators we have from MongoDB, it's time to think about crafting more advanced filters. To do so, we can use AND and OR operators... but we have a couple of different flavors:

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Empty;

filter = filterBuilder.And(
    filter, 
    filterBuilder.Eq("Name", "Nick Cosentino"));
filter = filterBuilder.And(
    filter, 
    filterBuilder.Gte("Age", 30));

In the code example above, we start with an empty filter and assign it to a filter variable. From there, we use the And() method on the FilterDefinitionBuilder to combine in an Eq() filter followed by a Gte() filter. Keep in mind, this example shows combining filters via AND but we can also OR the filters together.

Another example does away with the method calls and uses &= and |= for AND and OR respectively. In my opinion, this is a much more legible way to write filters:

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Empty;
filter &= filterBuilder.Eq("Name", "Nick Cosentino");
filter &= filterBuilder.Gte("Age", 30);

Do keep in mind that once you start incorporating OR operators for your filters, you will want to consider the order of operations!


Wrapping Up MongoDB Filtering in C#

In this article, we got to look at a handful of different comparison operators available for MongoDB filtering in C#. We also got to see how we can combine such filters with two different approaches:

  • Method calls for And() and Or() on the FilterDefinitionBuilder
  • &= and |= on the filters themselves

In upcoming articles, we'll see more about how to leverage the filters for querying, updating, and deleting MongoDB documents! If you found this useful and you're looking for more learning opportunities, consider subscribing to my free weekly software engineering newsletter and check out my free videos on YouTube! Meet other like-minded software engineers and join my Discord community!