Docs 菜单
Docs 主页
/ / /
C#/ .NET驱动程序
/

Delete Documents

在本指南中,您可以了解如何使用删除操作从 MongoDB 集合中删除文档。

本指南中的示例使用sample_restaurants数据库中的restaurantscollection。此collection中的文档使用以下RestaurantAddressGradeEntry类作为模型:

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; }
}

注意

restaurants集合中的文档使用蛇形命名规则。本指南中的示例使用 ConventionPack 将集合中的字段反序列化为 Pascal 语句,并将它们映射到 Restaurant 类中的属性。

如需了解有关自定义序列化的更多信息,请参阅自定义序列化

此集合来自Atlas提供的 示例数据集。请参阅.NET/ C#驱动程序入门,学习;了解如何创建免费的MongoDB 集群并加载此示例数据。

使用删除操作来删除与查询过滤器匹配的文档。查询过滤器根据查询过滤器文档中的标准决定选择删除哪些记录。您可以通过以下方法在 MongoDB 中执行删除操作:

  • DeleteOne(),删除与查询筛选器匹配的第一个文档

  • DeleteMany(),删除与查询筛选器匹配的所有文档

以下代码演示如何使用同步 DeleteOne() 方法或异步 DeleteOneAsync() 方法删除一个文档。

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

以下代码演示如何使用同步 DeleteMany() 方法或异步 DeleteManyAsync() 方法删除所有匹配的文档。

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

提示

附加信息下方,使用这些方法查找可运行的示例。

DeleteOne()DeleteMany()方法要求您传递查询过滤,指定要匹配的文档。 有关如何构建查询过滤的更多信息,请参阅查询文档教程。

这两种方法都可以选择采用DeleteOptions类型作为附加参数,该参数表示可用于配置删除操作的选项。 如果您不指定任何DeleteOptions属性,驾驶员将不会自定义删除操作。

DeleteOptions 类型允许您使用以下属性配置选项:

属性
说明

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.

要为操作配置排序规则,请创建排序规则 类的实例。

下表描述了 Collation 构造函数接受的参数。它还列出了相应的类属性,您可以使用这些属性读取每个设置的值。

Parameter
说明
类属性

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

有关排序规则的更多信息,请参阅MongoDB Server手册中的排序规则页面。

以下代码使用 DeleteMany() 方法搜索“borough_1”索引,并删除 address.street 字段值包含短语“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

提示

如果前面的示例使用DeleteOne()方法而不是DeleteMany() ,则驾驶员将删除26匹配文档中的第一个。

DeleteOne()DeleteMany()方法返回DeleteResult类型。 此类型包含DeletedCount属性(指示已删除的文档数)和IsAcknowledged属性(指示结果是否得到确认)。 如果查询过滤与任何文档都不匹配,则不会删除任何文档,并且DeletedCount为0 。

有关删除操作的可运行示例,请参阅以下用法示例:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

替换文档

在此页面上