更新文档
在此页面上
您可以通过调用 update_one() 来更新集合中的文档。Collection
方法(针对 实例)。
将以下参数传递给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