删除多个文档
您可以通过在 实例上调用 delete_many() Collection
方法,在单个操作中从集合中删除多个文档。
将query筛选器传递给delete_many()
方法,以删除collection中与筛选器匹配的文档。如果不包含筛选器,MongoDB 将删除collection中的所有文档。
delete_many()
方法返回 DeleteResult 类型。此类型包含有关删除操作的信息,例如删除的文档总数。
要学习;了解有关删除操作的更多信息,请参阅删除文档指南。
提示
要删除collection中的所有文档,请考虑在实例上调用drop()
Collection
方法。要了解有关drop()
方法的更多信息,请参阅数据库和collection指南的删除collection部分。
例子
此示例从 sample_restaurants
数据库的 restaurants
集合中删除与查询过滤匹配的所有文档。 delete_many()
方法删除 borough
字段值为 "Manhattan"
且 address.street
字段值为 "Broadway"
的文档。
您可以将 restaurants
集合中的文档作为 Document
类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T>
类型参数替换为以下值之一:
<Document>
:将集合文档作为BSON文档进行访问<Restaurant>
:将集合文档作为Restaurant
结构的实例进行访问,该结构在代码顶部定义
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use mongodb::{ bson::{ Document, doc }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Address { street: String, city: String, } struct Restaurant { name: String, borough: String, address: Address, } 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 }; struct Address { street: String, city: String, } 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