更新多个文档
您可以通过调用update_many() 方法在Collection
实例上。
将以下参数传递给 update_many()
方法
查询过滤器,指定匹配的条件
更新文档,指定对所有匹配文档进行的更新
update_many()
方法返回一个 UpdateResult 类型,包含有关更新操作结果的信息,例如修改的文档数量。
要了解更多关于 update_many()
方法的知识,请参阅修改文档指南中的更新文档 部分。
示例
本示例更新了sample_restaurants
数据库中restaurants
集合的文档。使用update_many()
方法将near_me
字段添加到那些address.street
字段的值为"Sullivan Street"
并且borough
字段的值为"Manhattan"
的文档中。
您可以将restaurants
集合中的文档作为Document
类型或自定义数据类型的实例访问。要指定哪个数据类型表示集合的数据,请将高亮行的<T>
类型参数替换为以下值之一
<Document>
:以BSON文档的形式访问集合文档。<Restaurant>
:以在代码顶部定义的Restaurant
结构体的实例访问集合文档。
选择异步或同步选项卡以查看每个运行时的相应代码
use std::env; use mongodb::{ bson::doc, Client, Collection }; use bson::Document; use serde::{ Deserialize, Serialize }; struct Address { street: String, city: String, } struct Restaurant { name: String, borough: String, address: Address, } 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! { "address.street": "Sullivan Street", "borough": "Manhattan" }; let update = doc! { "$set": doc! { "near_me": true } }; let res = my_coll.update_many(filter, update).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 } }; use serde::{ Deserialize, Serialize }; struct Address { street: String, city: String, } struct Restaurant { name: String, borough: String, address: Address, } 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! { "address.street": "Sullivan Street", "borough": "Manhattan" }; let update = doc! { "$set": doc! { "near_me": true } }; let res = my_coll.update_many(filter, update).run()?; println!("Updated documents: {}", res.modified_count); Ok(()) }
// Your values might differ Updated documents: 22