How To Delete Documents From MongoDB In C# – What You Need To Know
Tags: mongodb, database, csharp, coding
Published: 2024-04-03 16:00:00

In my recent blogs, I’ve covered many of the basics of working with MongoDB from C#. I highly suggest you check out [how you can perform filtering of documents from MongoDB in C#](https://www.devleader.ca/2024/03/24/mongodb-filtering-in-c-beginners-guide-for-easy-filters/) since it will be a stepping stone before we get into deleting. In this article, I’ll cover how to delete documents from MongoDB in C# and the code examples will assume you have some basic MongoDB filtering knowledge already

If you want to incorporate MongoDB into your C# application and want to understand how to delete documents, read on!

---

## **Basics of MongoDB in CSharp**

To get started with MongoDB in C#, you’ll need to install the MongoDB driver for C#. This driver provides a high-level API for interacting with MongoDB from your C# code, and it’s [as simple as getting the NuGet package installed](https://www.nuget.org/packages/MongoDB.Driver). Once you have the driver installed, you can establish a connection to your MongoDB database and start working with documents.

If you’re using something like MongoDB Atlas and the desktop tool Compass, these should walk you through how you can get your connection string sorted out. However, if you’re using other hosting providers or hosting locally, you’ll need to follow relevant instructions for how to get your connection string set up so that you can connect properly. Unfortunately, I can’t document this for every possibility 🙂

In MongoDB, data is stored in collections, which are analogous to tables in a relational database. Maybe not structurally or how they’re implemented, but conceptually this is the easiest way to think about them. Each document within a collection is a JSON-like object that can have different fields and values. In SQL databases, we’re used to thinking about rows representing our data, and a single row spans multiple columns in a table. However, in a document database like MongoDB, the “row” is an entire document, which can be hierarchical data. To delete a document from MongoDB, you need to specify the collection and the document you want to delete.

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

---

## **Before We Delete Documents From MongoDB In CSharp…**

Before getting ahead of ourselves here with deleting documents, it’s important to make sure we understand how filtering works. This is because to delete the correct documents, we need to make sure that we can identify WHICH documents we need to delete! In production, you really need to get this right. If you’re not filtering properly, you could be risking dropping all sorts of incorrect documents from your database… and I don’t even want to think about the fun times ahead for recovering that.

If you need a primer on how to filter, you can read [this article on filtering MongoDB records from C#](https://www.devleader.ca/2024/03/24/mongodb-filtering-in-c-beginners-guide-for-easy-filters/). And if that’s not straightforward or aligned with your learning style, you may find [this video on using C# to filter MongoDB records]() of better value:

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

---

## **DeleteOne and DeleteOneAsync in MongoDB**

The `DeleteOne` method deletes a single document that matches the specified filter criteria. It’s important to note here that there’s nothing that forces you to write a filter that will match a single document and if you do intend to potentially match multiple documents we’ll see more about that in the next section

The MongoDB C# driver allows you to write a filter that’s empty to match EVERY document and call `DeleteOne`. But what would you expect to happen in this case? You’re going to match every document with the filter but the method call will still only delete one document. Is it the document you expect? Probably by definition, no, if you wrote a filter that matches multiple. Try to pay special attention to this!

Here’s a simple example of calling the `DeleteOne` method, and an important callout that there is an async version as well:

```csharp
var filter = Builders<MyDocument>.Filter.Eq("fieldName", "fieldValue");
var result = collection.DeleteOne(filter);

// async version
// var result = await collection.DeleteOneAsync(filter);
```

The result that is returned has a matched and deleted count that we can investigate. It’s worth noting in all of my experience so far that even if your filter matches MANY items, if you call `DeleteOne` it will at most show you a matched count of one still. As a result, this does not seem to be a reliable way to tell if your filter would have (or did) match multiple items and still only delete one.

---

## **DeleteMany and DeleteManyAsync in MongoDB**

Much like the previous example, `DeleteMany` and `DeleteManyAsync` behave similarly except that they are intended to be used with and support handling the deletion of multiple documents. `DeleteOne` will not throw an exception if the filter matched multiple documents, but if your intention is truly to be able to support multiple document deletion, these are the methods to use instead.

The code example below shows the sync and async variations:

```csharp
var filter = Builders<MyDocument>.Filter.Gte("fieldValue", minValue);
var result = collection.DeleteOne(filter);

// async version
//var result = await collection.DeleteOneAsync(filter);
```

Like `DeleteOne`, the result that we have to work with has the matched and deleted counts. However, unlike `DeleteOne`, the match count will indicate how many items truly did match the filter and not be limited to one at most. Again, use these method variations if you need to support multiple documents matching the filter.

---

## **FindOneAndDelete and FindOneAndDeleteAsync Methods**

`FindOneAndDelete` and the async variation are very much like `DeleteOne` method variations. These methods will perform a delete of up to one document matching the filter, but the interesting difference is the return value. The return type provides us access to the document that matched the filter and was deleted from MongoDB.

Here’s a code example of `FindOneAndDelete`:

```csharp
var filter = Builders<MyDocument>.Filter.Gte("fieldValue", minValue);
var result = collection.FindOneAndDelete(filter);

// async version
//var result = await collection.FindOneAndDeleteAsync(filter);
```

The result that comes back from this method call is the document that matched the filter and was deleted. This can be especially useful if you need to work with the record information and want to save yourself an extra query and logic to validate the response.

If you want to see this method along with the ones from the earlier section in action, you can check out [this video on how to delete documents from MongoDB in C#](https://youtu.be/wK2TlqTY3nw):

{% embed https://youtu.be/wK2TlqTY3nw %}
---

## **Wrapping Up How To Delete Documents From MongoDB In CSharp**

And now you have all of the basics covered on how to delete documents from MongoDB in C#! In this article, I covered several variations that are all very similar and only need a filter definition to work with:

* DeleteOne: deletes up to one single document based on the filter
    
* DeleteMany: deletes all of the matching documents based on the filter
    
* FindOneAndDelete: deletes up to one single document based on the filter and returns the matching document that was deleted
    

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/)!

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

---

### 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 courses? Check out my 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)