您可以通过在 Collection 实例上调用 update_many() 方法来更新集合中的多个文档。
将以下参数传递给update_many()方法:
查询筛选器,指定要匹配的条件
更新文档,指定对所有匹配文档进行的更新
update_many() 方法返回 UpdateResult 类型,其中包含有关更新操作结果的信息,例如已修改的文档数。
要学习;了解有关update_many()方法的更多信息,请参阅修改文档指南中的更新文档部分。
例子
此示例更新sample_restaurants数据库的restaurants集合中的文档。
以下代码将near_me字段添加到address.street字段值为"Sullivan Street"且borough字段为"Manhattan"的文档中。
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use std::env; use mongodb::{ bson::doc, Client, Collection }; use bson::Document; 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! { "address.street": "Sullivan Street", "borough": "Manhattan" }; let update = doc! { "$set": doc! { "near_me": true } }; let res = my_coll.update_many(filter, update, None).await?; println!("Updated documents: {}", res.modified_count); Ok(()) }
// Your values might differ Updated documents: 22
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! { "address.street": "Sullivan Street", "borough": "Manhattan" }; let update = doc! { "$set": doc! { "near_me": true } }; let res = my_coll.update_many(filter, update, None)?; println!("Updated documents: {}", res.modified_count); Ok(()) }
// Your values might differ Updated documents: 22