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# 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!
Remember to check out these platforms:
// FIXME: social media icons coming back soon!
Basics of MongoDB in C#
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. 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.
Before We Delete Documents From MongoDB In C#...
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#. 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:
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:
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:
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
:
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#:
Wrapping Up How To Delete Documents From MongoDB In C#
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 and check out my free videos on YouTube! Meet other like-minded software engineers and join my Discord community!
Affiliations
These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!
- BrandGhost: My social media content and scheduling tool that I use for ALL of my content!
- RackNerd: Cheap VPS hosting options that I love for low-resource usage!
- Contabo: Affordable VPS hosting options!
- ConvertKit: The platform I use for my newsletter!
- SparkLoop: Helps add value to my newsletter!
- Opus Clip: Tool for creating short-form videos!
- Newegg: For all sorts of computer components!
- Bulk Supplements: Huge selection of health supplements!
- Quora: I answer questions when folks request them!
Frequently Asked Questions: How To Delete Documents From MongoDB In C#
What is MongoDB?
MongoDB is a popular NoSQL database that provides high performance, scalability, and flexibility for managing unstructured data.
Why is deleting documents important in MongoDB?
Deleting documents allows you to remove records from MongoDB that are no longer needed. This ensures you can your data up-to-date and keep only what's relevant inside of your persistent storage.
What are the different ways to delete documents in MongoDB using C#?
In C#, you can delete documents from MongoDB using methods such as DeleteOne, DeleteMany, and FindOneAndDelete. These methods provide different approaches for deleting individual or multiple documents efficiently and have async variations.
How does the DeleteOne method work in C# for deleting MongoDB documents?
The DeleteOne method allows you to delete a single document that matches a specified filter. If multiple documents match the filter, it will still only delete one of them.
How is the DeleteMany method used for MongoDB in C#?
The DeleteMany method is used to delete multiple documents that match a given filter. This method is suitable for deleting a batch of documents at once, which is especially valuable if the provided filter intends to match multiple documents.