Docs Menu
Docs Home
/ / /
C#/.NET
/

Delete Documents

In this guide, you can learn how to remove documents from your MongoDB collections using delete operations.

The examples in this guide use the restaurants collection from the sample_restaurants database. The documents in this collection use the following Restaurant, Address, and GradeEntry classes as models:

public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }
}
public class Address
{
public string Building { get; set; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
}
public class GradeEntry
{
public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }
}

Note

The documents in the restaurants collection use the snake-case naming convention. The examples in this guide use a ConventionPack to deserialize the fields in the collection into Pascal case and map them to the properties in the Restaurant class.

To learn more about custom serialization, see Custom Serialization.

This collection is from the sample datasets provided by Atlas. See the Get Started with the .NET/C# Driver to learn how to create a free MongoDB cluster and load this sample data.

Use delete operations to remove documents that match a query filter. The query filter determines which records are selected for deletion based on the criteria in the query filter document. You can perform delete operations in MongoDB with the following methods:

  • DeleteOne(), which deletes the first document that matches the query filter

  • DeleteMany(), which deletes all documents that match the query filter

The following code shows how to use the asynchronous DeleteOneAsync() method or the synchronous DeleteOne() method to delete one document.

var result = await _restaurantsCollection.DeleteOneAsync(filter);
var result = _restaurantsCollection.DeleteOne(filter);

The following code shows how to use the asynchronous DeleteManyAsync() method or the synchronous DeleteMany() method to delete all matched documents.

var result = await _restaurantsCollection.DeleteManyAsync(filter);
var result = _restaurantsCollection.DeleteMany(filter);

Tip

Find runnable examples using these methods under additional information.

The DeleteOne() and DeleteMany() methods require you to pass a query filter specifying which documents to match. More information on how to construct a query filter is available in the Query Documents tutorial.

Both methods optionally take a DeleteOptions type as an additional parameter, which represents options you can use to configure the delete operation. If you don't specify any DeleteOptions properties, the driver does not customize the delete operation.

The DeleteOptions type allows you to configure options with the following properties:

Property
Description

Collation

Gets or sets the type of language collation to use when sorting results. See the Collation section of this page for more information.

Comment

Gets or sets the comment for the operation. See the delete command fields for more information.

Hint

Gets or sets the index to use to scan for documents. See the delete statements for more information.

Let

Gets or sets the let document. See the delete command fields for more information.

To configure collation for your operation, create an instance of the Collation class.

The following table describes the parameters that the Collation constructor accepts. It also lists the corresponding class property that you can use to read each setting's value.

Parameter
Description
Class Property

locale

Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(Optional) Specifies whether to include case comparison.

When this argument is true, the driver's behavior depends on the value of the strength argument:

- If strength is CollationStrength.Primary, the driver compares base characters and case.
- If strength is CollationStrength.Secondary, the driver compares base characters, diacritics, other secondary differences, and case.
- If strength is any other value, this argument is ignored.

When this argument is false, the driver doesn't include case comparison at strength level Primary or Secondary.

Data Type: boolean
Default: false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If this argument is true, the driver compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the driver treats the values as 10 and 2, and finds 10 to be greater.

If this argument is false or excluded, the driver compares numeric strings as strings. For example, when comparing the strings "10" and "2", the driver compares one character at a time. Because "1" is less than "2", the driver finds "10" to be less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: boolean
Default: false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

For more information about collation, see the Collation page in the MongoDB Server manual.

The following code uses the DeleteMany() method to search on the "borough_1" index and delete all documents where the address.street field value includes the phrase "Pearl Street":

var filter = Builders<Restaurant>.Filter
.Regex("address.street", "Pearl Street");
DeleteOptions opts = new DeleteOptions { Hint = "borough_1" };
Console.WriteLine("Deleting documents...");
var result = _restaurantsCollection.DeleteMany(filter, opts);
Console.WriteLine($"Deleted documents: {result.DeletedCount}");
Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");
Deleting documents...
Deleted documents: 26
Result acknowledged? True

Tip

If the preceding example used the DeleteOne() method instead of DeleteMany(), the driver would delete the first of the 26 matched documents.

The DeleteOne() and DeleteMany() methods return a DeleteResult type. This type contains the DeletedCount property, which indicates the number of documents deleted, and the IsAcknowledged property, which indicates if the result is acknowledged. If the query filter does not match any documents, no documents are deleted and DeletedCount is 0.

For runnable examples of the delete operations, see the following usage examples:

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

Back

Replace Documents

On this page