您可以通过在 实例上调用 replace_one() Collection
方法来替换集合中的文档。
将以下参数传递给replace_one()
方法:
查询筛选器,指定要匹配的条件
替换文档,其中包含将替换第一个匹配文档的字段和值
replace_one()
方法返回 UpdateResult 类型,其中包含有关替换操作结果的信息,例如已修改文档的数量。
要学习;了解有关replace_one()
方法的更多信息,请参阅修改文档指南的替换文档部分。
例子
此示例替换sample_restaurants
数据库的restaurants
collection中的文档。Restaurant
该示例使用具有fieldsname
borough
、 和cuisine
字段的 结构体来对collection中的文档进行建模。
以下代码将name
字段的值为"Landmark Coffee Shop"
的文档替换为新文档。MongoDB 会替换与查询筛选器匹配的第一个文档。
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
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?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "name": "Landmark Coffee Shop" }; let replacement = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; let res = my_coll.replace_one(filter, replacement, None).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)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "name": "Landmark Coffee Shop" }; let replacement = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; let res = my_coll.replace_one(filter, replacement, None)?; println!("Replaced documents: {}", res.modified_count); Ok(()) }
Replaced documents: 1