删除文档
您可以通过在 实例上调用 delete_one() Collection
方法从集合中删除文档。
将查询筛选器传递给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