MongoDB Filtering in C# – Beginner’s Guide For Easy Filters
Tags: mongodb, database, coding, dotnet
Published: 2024-04-01 16:00:00

[MongoDB Filtering in C# – Beginner’s Guide For Easy Filters](https://www.devleader.ca/2024/03/24/mongodb-filtering-in-c-beginners-guide-for-easy-filters/) appeared first on [Dev Leader](https://www.devleader.ca).

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#](https://www.devleader.ca/2024/03/22/mongodb-in-c-simplified-guide-for-inserting-data/) [and wanted to follow up with this article’s](https://www.devleader.ca/2024/03/22/mongodb-in-c-simplified-guide-for-inserting-data/) topic: MongoDB filtering in C#. Filtering is important when it comes to MongoDB, not only to be able to query for records… but also 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 t](https://www.devleader.ca/2024/02/22/c-for-beginners-5-simplified-concepts-in-c/)o working with MongoDB filters. You’ll see simplified code examples demonstrating how to construct filters so when it’s time to query, dele[te, or update you’ll be all set.](https://www.devleader.ca/2024/03/22/mongodb-in-c-simplified-guide-for-inserting-data/)

---

## **MongoDB Filtering in CSharp 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#:

```csharp
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#](https://youtu.be/2zXvDW2YFcg):

{% embed https://youtu.be/2zXvDW2YFcg %} 

---

## **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:

```csharp
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:

```csharp
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:

```csharp
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 CSharp**

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:

```csharp
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:

```csharp
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 CSharp**

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](https://www.devleader.ca/2024/03/26/how-to-delete-documents-from-mongodb-in-c-what-you-need-to-know/)! If you found this useful and you’re looking for more learning opportunities, consider [subscribing to my free weekly software engineering newsletter](https://subscribe.devleader.ca/) and check out my [free videos on YouTube](https://www.youtube.com/@devleader?sub_confirmation=1)! Meet other like-minded software engineers and [join my Discord community](https://www.devleader.ca/discord-community-access/)!

---

## Want More Dev Leader Content?

* Follow along on this platform if you haven’t already!    
* Subscribe to my free weekly software engineering and dotnet-focused newsletter. I include exclusive articles and early access to videos:  
    [**SUBSCRIBE FOR FREE**](https://subscribe.devleader.ca/)    
* Looking for cou[rses? Check out m](https://www.devleader.ca/2024/02/22/c-for-beginners-5-simplified-concepts-in-c/)y offerings:  
    [**VIEW COURSES**](https://devleader.ca/courses)    
* E-Books & other resources:  
    [**VIEW RESOURCES**](https://products.devleader.ca/)    
* Watch hundreds of full-length videos on my YouTube channel:  
    [**VISIT CHANNEL**](https://youtube.com/@devleader?sub_confirmation=1)    
* Visit my website for hundreds of articles on various software engineering topics (including code snippets):  
    [**VISIT WEBSITE**](https://devleader.ca/)    
* Check out the repository with many code examples from my articles and videos on GitHub:  
    [**VIEW REPOSITORY**](https://github.com/ncosentino/DevLeader)
    

{% embed https://weekly.devleader.ca/embed %}