Quick Start: C# and MongoDB - Delete operations

Ken W. Alger

#C#/.NET
C Sharp Quick Start

This post will cover the last of the CRUD operations, Delete. If you've been following along with this series, I've been using sample data available in MongoDB Atlas, specifically the grades collection in the sample_training database. In the Create post, a new record was added to the data set.

To continue along with the student story, let's take a look at how what would happen if the student dropped the course and had to have their grades deleted. Once again, the MongoDB driver for C# makes it a breeze. And, it provides both sync and async options for the operations.

Deleting Data

The first step in the deletion process is to create a filter for the document(s) that need to be deleted. In the example for this series, I've been using a document with a student_id value of 10000 to work with. Since I'll only be deleting that single record, I'll use the DeleteOne() method (for async situations the DeleteOneAsync() method is available). However, when a filter matches more than a single document and all of them need to be deleted, the DeleteMany() or DeleteManyAsync method can be used.

Here's the record I want to delete.

            {
                { "student_id", 10000 },
                { "scores", new BsonArray
                    {
                    new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
                    new BsonDocument{ {"type", "quiz"}, {"score", 84.92381029342834 } },
                    new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
                    new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
                    }
                },
                { "class_id", 483}
            };

I'll define the filter to match the student_id equal to 10000 document:

var deleteFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);

Assuming that we have a collection variable assigned to for the grades collection, we next pass the filter into the DeleteOne() method.

collection.DeleteOne(deleteFilter);

If that command is run on the grades collection, the document with student_id equal to 10000 would be gone. Note here that DeleteOne() will delete the first document in the collection that matches the filter. In our example dataset, since there is only a single student with a student_id equal to 10000, we get the desired results.

For the sake of argument, let's imagine that the rules for the educational institution are incredibly strict. If you get below a score of 60 on the first exam, you are automatically dropped from the course. We could use a for loop with DeleteOne() to loop through the entire collection, find a single document that matches an exam score of less than 60, delete it, and repeat. Recall that DeleteOne() only deletes the first document it finds that matches the filter. While this could work, it isn't very efficient as multiple calls to the database are made. How do we handle situations that require deleting multiple records then? We can use DeleteMany().

Multiple Deletes

Let's define a new filter to match the exam score being less than 60:

var deleteLowExamFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("scores",
     new BsonDocument { { "type", "exam" }, {"score", new BsonDocument { { "$lt", 60 }}}
});

With the filter defined, we pass it into the DeleteMany() method:

collection.DeleteMany(deleteLowExamFilter);

With that command being run, all of the student record documents with low exam scores would be deleted from the collection.

Check out the gist for all of the CRUD commands wrapped into a single file.

Wrap Up

This C# Quick Start series has covered the various CRUD Operations (Create, Read, Update, and Delete) operations in MongoDB using basic BSON Documents. We've seen how to use filters to match specific documents that we want to read, update, or delete. This series has, thus far, been a gentle introduction to C Sharp and MongoDB.

BSON Documents are not, however, the only way to be able to use MongoDB with C Sharp. In our applications, we often have classes defining objects. We can map our classes to BSON Documents to work with data as we would in code. I'll take a look at mapping in the next part of this C Sharp Quick Start series.

Get started with an M0 cluster on MongoDB Atlas today. It's free forever and you'll be able to work alongside this blog series.

Other articles in this Quick Start C# and MongoDB series: