删除多个文档
您可以通过调用来在一个操作中从集合中删除多个文档delete_many() 方法在Collection
实例上。
向 delete_many()
方法传递一个查询过滤器,以删除匹配该过滤器的集合中的文档。如果不包含过滤器,MongoDB 将删除集合中的所有文档。
delete_many()
方法返回一个 DeleteResult 类型。此类型包含有关删除操作的信息,例如删除的文档总数。
有关删除操作的更多信息,请参阅删除文档指南。
技巧
要删除集合中的所有文档,可以考虑在 Collection
实例上调用 drop()
方法。有关 drop()
方法的更多信息,请参阅数据库和集合指南中的删除集合部分。
示例
本示例从sample_restaurants
数据库中的restaurants
集合中删除所有匹配查询筛选条件的文档。
本示例将查询筛选条件作为参数传递给delete_many()
方法。筛选条件匹配borough
字段的值为“Manhattan”且address.street
字段的值为“Broadway”的文档。
选择异步或同步选项卡以查看每个运行时对应的代码
use mongodb::{ bson::{ Document, doc }, Client, Collection }; async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Document> = 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 } }; fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Document> = 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