对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

Delete Documents

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

本指南中的示例使用 sample_restaurants 数据库中的 restaurants 集合。此集合中的文档使用以下 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 类中的属性。

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

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.

使用删除操作来删除与查询筛选条件匹配的文档。查询筛选条件根据查询筛选条件文档中的标准决定选择删除哪些记录。您可以通过以下方法在 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

获取或设置操作的注释。有关详情,请参阅删除命令字段

Hint

获取或设置用于扫描文档的索引。有关详细信息,请参阅删除语句

Let

获取或设置 let 文档。有关详情,请参阅删除命令字段

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

下表描述了 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

(可选)指定是否包含大小写比较。

当此参数为 true 时,驱动程序的行为取决于 strength 参数的值:

- 如果 strengthCollationStrength.Primary,则驱动程序会比较基本字符和大小写。
- 如果 strengthCollationStrength.Secondary,则驱动程序会比较基本字符、变音符、其他次要差异和大小写。
- 如果 strength 为任何其他值,则会忽略此参数。

当此参数为 false 时,驱动程序不会在强度级别 PrimarySecondary 包含大小写比较。

数据类型boolean
默认值false

CaseLevel

caseFirst

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

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

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

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(可选)指定驾驶员是否将数字字符串作为数字进行比较。如果此参数为

true10210210

false102,则驾驶员将数字字符串作为数字进行比较。示例,在比较字符串1 2102"" 和和“”,则驾驶员会将这些值视为 和 ,并发现 更大。如果此参数为 或已排除,则驾驶员会将数字字符串作为字符串进行比较。示例,在比较字符串 ""

和和“”,驾驶员一次比较一个字符。因为""小于“”,则驾驶员会找到“”小于“”。有关更多信息,请参阅MongoDB Server手册中的排序规则限制。数据类型:

boolean
默认值:false

NumericOrdering

alternate

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

Data Type: CollationAlternate
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.

Data Type: CollationMaxVariable
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

(可选)指定包含变音符号的字符串是否从字符串的后部到前部排序。

数据类型boolean
默认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}");

提示

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

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

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

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