Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/ / /

Delete Documents

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

本指南包括以下部分:

  • 示例的样本数据显示了删除操作示例使用的样本数据

  • 删除操作描述了如何使用驱动程序执行删除操作

  • 附加信息提供了本指南中提到的类型和方法的资源和 API 文档链接

本指南中的示例使用以下样本文档。 每个文档代表商店库存中的一个商品,并包含有关其分类和单价的信息:

{ "item": "trowel", "category": "garden", "unit_price": 9.89 },
{ "item": "placemat", "category": "kitchen", "unit_price": 3.19 },
{ "item": "watering can", "category": "garden", "unit_price": 11.99 }

Rust 驱动程序提供了 delete_one()delete_many()方法来执行删除操作。

delete_one()delete_many()方法将查询筛选器作为参数。 查询筛选器由构成要匹配的文档条件的字段和值组成。

您还可以选择将DeleteOptions类型作为参数传递给任一方法。 您可以在DeleteOptions实例中指定设置来配置删除操作。 要使用每个设置的默认值,请将值None指定为选项参数。

注意

实例化选项

Rust 驱动程序实现了用于创建许多不同类型的 Builder 设计模式,包括DeleteOptions 。 您可以使用每种类型的builder()方法,通过逐个链接选项构建器函数来构造选项实例。

下表描述了您可以在DeleteOptions实例中指定的设置:

选项
说明

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

write_concern

The write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see Write Concern in the Server manual.

Type: WriteConcern

hint

The index to use for the operation. To learn more about indexes, see Indexes in the Server manual. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Hint
Default: None

let_vars

A map of parameters and values. These parameters can be accessed as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

An arbitrary Bson value tied to the operation to trace it through the database profiler, currentOp, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Bson
Default: None

以下代码展示了如何构造DeleteOptions实例并将其传递给delete_one()方法:

let opts: DeleteOptions = DeleteOptions::builder().comment(bson!("hello!")).build();
let res = my_coll.delete_one(filter, opts).await?;

delete_one()delete_many()方法返回DeleteResult类型。 此类型包含deleted_count属性,该属性描述已删除的文档数量。 如果没有文档与您指定的查询筛选器匹配,则删除操作不会删除任何文档,并且deleted_count的值为0

此示例演示如何使用以下参数调用delete_many()方法:

  • 查询筛选器,匹配category值为"garden"的文档

  • 使用_id_索引作为删除操作提示的DeleteOptions实例

let filter = doc! { "category": "garden" };
let hint = Hint::Name("_id_".to_string());
let opts: DeleteOptions = DeleteOptions::builder().hint(hint).build();
let res = my_coll.delete_many(filter, opts).await?;
println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 2

注意

如果在前面的代码示例中使用delete_one()方法而不是delete_many() ,则驱动程序仅删除与查询筛选器匹配的两个文档中的第一个。

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

要了解有关本指南中操作的更多信息,请参阅以下文档:

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

后退

Modify

在此页面上