Introduction to MongoDb with .NET part 20: deletions in the MongoDb driver


In the previous post we discussed how to perform updates via the MongoDb .NET driver. Update operations can be divided into replacements and “true” updates. A replacement is where an existing document is replaced by another and only the _id field stays constant. A “true” update is really how we normally think updates should happen, i.e. only specific properties are overwritten in the matching document(s). Both update types are represented by a number of methods in the driver such as UpdateOne or FindOneAndReplace or UpdateMany.

In this post we’ll close the CRUD circle and look at deletions in the driver. After all we’ve learnt about filter definitions and options it will be a breeze to go through deletions.


Deletions can be performed via a number of functions similar to updates. Here is the list of currently available functions related to deletes. You’ll be able to follow their purpose based on what we’ve seen about updates.

  • DeleteOne with a filter definition
  • DeleteOne extension method with LINQ expressions for filters
  • DeleteMany with a filter defintion
  • DeleteMany extension with a LINQ filter
  • FindOneAndDelete: an atomic operation to find a single document and delete it, similar to FindOneAndUpdate
  • All of the above have async counterparts such as DeleteManyAsync and FindOneAndDeleteAsync

The Delete* methods all return a DeleteResult whereas FindOneAndDelete returns the document that was deleted or null of none was deleted.

Let’s remove one of the dummy restaurants by name using DeleteOne with a filter definition:

ModelContext modelContext = ModelContext.Create(new ConfigFileConfigurationRepository(), new AppConfigConnectionStringRepository());
DeleteResult deleteResult = modelContext.Restaurants.DeleteOne(Builders<RestaurantDb>.Filter.Eq(r => r.Name, "BrandNewMexicanKing"));

We’ve already seen the filter definition builder in action numerous times so I won’t go through it again. The DeleteResult exposes the DeletedCount property which obviously stores the number of deleted documents. In the above example it will be one and with DeleteOne it can only be 0 or 1 of course.

DeleteMany works in the same manner but all documents matching a query will be removed. You can easily figure out how it is used.

Let’s instead look at the FindOneAndDelete method. Here’s an example including the FindOneAndDeleteOptions object:

ModelContext modelContext = ModelContext.Create(new ConfigFileConfigurationRepository(), new AppConfigConnectionStringRepository());
FindOneAndDeleteOptions<RestaurantDb, RestaurantDb> findOneAndDeleteOptions = new FindOneAndDeleteOptions<RestaurantDb, RestaurantDb>()
	Sort = Builders<RestaurantDb>.Sort.Descending(r => r.Id)
RestaurantDb deleted = modelContext.Restaurants.FindOneAndDelete(Builders<RestaurantDb>.Filter.Eq(r => r.Name, "BrandNewMexicanKing"), findOneAndDeleteOptions);
Console.WriteLine(deleted == null);

The FindOneAndDeleteOptions object exposes a Sort property which has the same purpose as in FindOneAndReplaceOptions, i.e. it offers some control over which matching document will be deleted. The above example specifies that the matching documents will be sorted by Id in ascending order and the top item of that list will be removed.

Since we’ve already removed the restaurant called BrandNewMexicanKing the function returns null, i.e. deleted == null will the True.

We’ll take up a special wrapper for multiple insert, update and delete operations called bulk writes in the next post.

You can view all posts related to data storage on this blog here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Introduction to MongoDb with .NET part 20: deletions in the MongoDb driver

  1. Anil Jain says:

    Your articles in Mongodb with .NET are simply superb!!

    Thanks a lot!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: