对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

更新文档

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

将以下参数传递给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