您可以通过在 Collection 实例上调用 update_one() 方法来更新集合中的文档。
将以下参数传递给update_one()方法:
- 查询筛选器,指定要匹配的条件 
- 更新文档,指定对第一个匹配文档进行的更新 
update_one() 方法返回 UpdateResult 类型,其中包含有关更新操作结果的信息,例如已修改的文档数。
要学习;了解有关update_one()方法的更多信息,请参阅修改文档指南中的更新文档部分。
例子
此示例更新 sample_restaurants数据库的 restaurants集合中的文档。 update_one() 方法将 price字段添加到 name字段值为 "Spice Market" 的第一个文档。
您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T> 类型参数替换为以下值之一:
- <Document>:将集合文档作为BSON文档进行访问
- <Restaurant>:将集合文档作为- Restaurant结构的实例进行访问,该结构在代码顶部定义
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use std::env; use mongodb::{     bson::{ Document, doc },     Client,     Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant {     name: String,     price: 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! { "name": "Spice Market" };     let update = doc! { "$set": doc! {"price": "$$$"} };     let res = my_coll.update_one(filter, update).await?;     println!("Updated documents: {}", res.modified_count);     Ok(()) } 
Updated documents: 1 
use std::env; use mongodb::{     bson::{ Document, doc },     sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant {     name: String,     price: 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! { "name": "Spice Market" };     let update = doc! { "$set": doc! {"price": "$$$"} };     let res = my_coll.update_one(filter, update).run()?;     println!("Updated documents: {}", res.modified_count);     Ok(()) } 
Updated documents: 1