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