替换文档
您可以通过调用replace_one() 方法,用于对Collection
实例。
将以下参数传递给 replace_one()
方法
查询过滤器,指定匹配条件
替换文档,包含要替换第一个匹配文档的字段和值
replace_one()
方法返回一个 UpdateResult 类型,包含有关替换操作结果的信息,例如修改的文档数。
有关 replace_one()
方法的更多信息,请参阅修改文档指南中的替换文档 部分。
示例
此示例替换了sample_restaurants
数据库中restaurants
集合中的一个文档。使用replace_one()
方法,将name
字段的值为"Landmark Coffee Shop"
的第一个文档替换为一个新的文档。
您可以将restaurants
集合的文档作为Document
类型或自定义数据类型的实例访问。要指定哪个数据类型表示集合的数据,请在突出显示的行上执行以下操作
要将集合文档作为BSON文档访问,将
<T>
类型参数替换为<Document>
,并将<struct or doc>
占位符替换为replace_doc
。要将集合文档作为
Restaurant
结构体的实例访问,将<T>
类型参数替换为<Restaurant>
,并将<struct or doc>
占位符替换为replace_struct
。Restaurant
结构体在代码文件顶部定义。
选择异步或同步选项卡以查看每个运行时的对应代码
use std::env; use mongodb::{ bson::doc, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: 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": "Landmark Coffee Shop" }; let replace_doc = doc! { "borough": "Brooklyn", "cuisine": "Café/Coffee/Tea", "name": "Harvest Moon Café", }; let replace_struct = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; // Replace <struct or doc> with the replace_struct or replace_doc variable let res = my_coll.replace_one(filter, <struct or doc>).await?; println!("Replaced documents: {}", res.modified_count); Ok(()) }
Replaced documents: 1
use std::env; use mongodb::{ bson::doc, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: 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": "Landmark Coffee Shop" }; let replace_doc = doc! { "borough": "Brooklyn", "cuisine": "Café/Coffee/Tea", "name": "Harvest Moon Café", }; let replace_struct = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; // Replace <struct or doc> with the replace_struct or replace_doc variable let res = my_coll.replace_one(filter, <struct or doc>).run()?; println!("Replaced documents: {}", res.modified_count); Ok(()) }
Replaced documents: 1