Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/

替换文档

您可以通过在 实例上调用 replace_one() Collection方法来替换集合中的文档。

将以下参数传递给replace_one()方法:

  • 查询筛选器,指定要匹配的条件

  • 替换文档,其中包含将替换第一个匹配文档的字段和值

replace_one()方法返回 UpdateResult 类型,其中包含有关替换操作结果的信息,例如已修改文档的数量。

要学习;了解有关replace_one()方法的更多信息,请参阅修改文档指南的替换文档部分。

此示例替换sample_restaurants数据库的restaurantscollection中的文档。Restaurant该示例使用具有fieldsname borough、 和cuisine 字段的 结构体来对collection中的文档进行建模。

以下代码将name字段的值为"Landmark Coffee Shop"的文档替换为新文档。MongoDB 会替换与查询筛选器匹配的第一个文档。

选择 AsynchronousSynchronous标签页,查看每个运行时的相应代码:

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
#[tokio::main]
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 };
#[derive(Serialize, Deserialize, Debug)]
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

后退

更新多个