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

Delete Documents

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

本指南包括以下部分:

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

{ "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()方法将查询筛选器作为参数。 查询筛选器由构成要匹配的文档条件的字段和值组成。

您可以通过将选项构建器方法链接到delete_one()delete_many()来修改删除操作方法的行为。 这些选项方法设立DeleteOptions结构体字段。

注意

设置选项

您可以通过将选项构建器方法直接链接到删除方法调用来设置 DeleteOptions 字段。如果使用的是早期版本的驱动程序,则必须通过将选项构建器方法链接到 builder() 方法来构造 DeleteOptions实例。然后,将选项实例作为参数传递给 delete_one()delete_many()

下表描述了DeleteOptions中可用的选项:

选项
说明

collation

对结果进行排序时使用的排序规则。要进一步了解排序规则,请参阅排序规则指南。

类型: Collation
默认: None

write_concern

操作的写关注(write concern)。如果您未设置此选项,则操作会继承为集合设置的写关注(write concern)。要了解有关写关注(write concern)的更多信息,请参阅服务器手册中的写关注(write concern)

类型:WriteConcern

hint

用于操作的索引。要了解有关索引的更多信息,请参阅服务器手册中的索引。此选项仅在连接到 MongoDB Server 4.4及更高版本时可用。

类型:Hint
默认:None

let_vars

参数和值的映射。这些参数可以作为聚合表达式中的变量进行访问。此选项仅在连接到 MongoDB Server 5.0 及更高版本时可用。

类型:Document

comment

与操作绑定的任意 Bson 值,可通过数据库分析器、currentOp 和日志进行追踪。此选项仅在连接到 MongoDB Server 4.4 及更高版本时可用。

类型:Bson
默认:None

以下代码展示了如何通过将comment()方法链接到delete_one()方法来设立comment字段:

let res = my_coll
.delete_one(filter)
.comment(bson!("hello!"))
.await?;

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

本部分提供以下删除操作的代码示例:

以下示例使用 delete_one() 方法删除item 值为 "placemat" 的文档:

let filter = doc! { "item": "placemat" };
let res = my_coll.delete_one(filter).await?;
println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 1

此示例从 sample_restaurants数据库的 restaurants集合中删除与查询过滤匹配的文档。 delete_one() 方法删除 name字段值为 "Haagen-Dazs"borough字段值为 "Brooklyn" 的第一个文档。

您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T> 类型参数替换为以下值之一:

  • <Document>:将集合文档作为BSON文档进行访问

  • <Restaurant>:将集合文档作为 Restaurant 结构的实例进行访问,该结构在代码顶部定义

选择AsynchronousSynchronous标签页,查看每个运行时的相应代码:

use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "name": "Haagen-Dazs" },
doc! { "borough": "Brooklyn" }
]
};
let result = my_coll.delete_one(filter).await?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
Deleted documents: 1
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "name": "Haagen-Dazs" },
doc! { "borough": "Brooklyn" }
]
};
let result = my_coll.delete_one(filter).run()?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
Deleted documents: 1

此示例将执行以下动作:

  • 调用delete_many()方法

  • 将查询过滤传递给delete_many() ,以匹配category的值为"garden"的文档

  • hint()方法链接到delete_many() ,以使用_id_索引作为删除操作的提示

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

注意

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

此示例从 sample_restaurants数据库的 restaurants集合中删除与查询过滤匹配的所有文档。 delete_many() 方法删除 borough字段值为 "Manhattan"address.street字段值为 "Broadway" 的文档。

您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T> 类型参数替换为以下值之一:

  • <Document>:将集合文档作为BSON文档进行访问

  • <Restaurant>:将集合文档作为 Restaurant 结构的实例进行访问,该结构在代码顶部定义

选择AsynchronousSynchronous标签页,查看每个运行时的相应代码:

use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
address: Address,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "borough": "Manhattan" },
doc! { "address.street": "Broadway" }
]
};
let result = my_coll.delete_many(filter).await?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
// Your values might differ
Deleted documents: 615
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
address: Address,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "borough": "Manhattan" },
doc! { "address.street": "Broadway" }
]
};
let result = my_coll.delete_many(filter).run()?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
// Your values might differ
Deleted documents: 615

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

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