Lesson 5: Deleting Documents in C# Applications / Learn
Deleting Documents in C# Applications
Review the following code, which demonstrates how to delete documents in MongoDB with C#.
Delete a Single Document
To delete a single document, use the DeleteOne() method, which accepts a query filter that matches the document that you want to delete. DeletedCount tells you how many documents were found by the filter and were deleted. Here's an example:
var accountsCollection =
database.GetCollection<Account>("Account");
var result = accountsCollection
.DeleteOne(a => a.AccountId == "MDB333829449");
Console.WriteLine(result.DeletedCount);
Delete a Single Document Asynchronously
To delete a single document asynchronously, use the DeleteOneAsync() method, which accepts a query filter that matches the document that you want to delete. We use a Builders class that matches a document based on the specified _id. Async methods can be used with builders or LINQ. Here's an example:
var filter = Builders<BsonDocument>
.Filter
.Eq("_id", new
ObjectId("63050518546c1e9d2d16ce4d"));
var accounts = await accountsCollection
.DeleteOneAsync(filter);
Delete Multiple Documents
To delete multiple documents, use the DeleteMany() method, which accepts a query filter that matches the documents that you want to delete. Once the documents are successfully deleted, the method returns an instance of DeleteResult, which enables the retrieval of information such as the number of documents that were deleted. For example:
var deleteResult = accountCollection
.DeleteMany(a => a.Balance < 500);
Console.WriteLine(result.DeleteCount)
Delete Multiple Documents Asynchronously
To delete multiple documents asynchronously, use the DeleteMany() method, which accepts a query filter that matches the documents that you want to delete. Once the documents are successfully deleted, the method returns an instance of DeleteResult, which enables the retrieval of information such as the number of documents that were deleted. We use a Builders class that matches a document based on the specified account_type. Async methods can be used with builders or LINQ. For example:
var filter = Builders<BsonDocument>
.Filter
.Eq("account_type", "checking");
var deleteResult = await accountsCollection
.DeleteManyAsync(filter);
Console.WriteLine(deleteResult.DeletedCount);