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

更新文档

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

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

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

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

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

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

此示例更新sample_restaurants数据库的restaurants集合中的文档。

以下代码将price字段添加到name字段值为"Spice Market"的文档中。 MongoDB 更新与查询筛选器匹配的第一个文档。

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

use std::env;
use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Document> = 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, None).await?;
println!("Updated documents: {}", res.modified_count);
Ok(())
}
Updated documents: 1
use std::env;
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
let my_coll: Collection<Document> = 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, None)?;
println!("Updated documents: {}", res.modified_count);
Ok(())
}
Updated documents: 1

后退

插入多个