文档菜单
文档首页
/ / /
Rust 驱动程序
/

更新文档

本页内容

  • 示例

您可以通过调用update_one() 方法在Collection 实例上。

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

  • 查询过滤器,指定匹配的条件

  • 更新文档,指定对第一个匹配文档要进行的更新

update_one() 方法返回一个 UpdateResult 类型,包含有关更新操作结果的信息,例如修改的文档数量。

要了解有关 update_one() 方法的更多信息,请参阅更新文档部分的修改文档指南。

此示例更新了 sample_restaurants 数据库中 restaurants 集合中的一个文档。使用 update_one() 方法向第一个 name 字段值为 "Spice Market" 的文档添加了 price 字段。

您可以将《restaurants》集合中的文档访问为《Document》类型或自定义数据类型的实例。要指定表示集合数据的类型,请在高亮行中将《`类型参数替换为以下值之一

  • <Document>:将集合文档作为BSON文档访问

  • <Restaurant>:将集合文档作为在代码顶部定义的《Restaurant》结构体的实例访问

选择异步同步选项卡以查看每个运行时对应的代码

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

返回

插入多个

本页内容