Docs Menu
Docs Home
/ / /
Rust Driver
/

Update Multiple Documents

You can update multiple documents in a collection by calling the update_many() method on a Collection instance.

Pass the following parameters to the update_many() method:

  • Query filter, which specifies the criteria to match

  • Update document, which specifies the updates to make to all matching documents

The update_many() method returns an UpdateResult type that contains information about the results of the update operation, such as the number of modified documents.

To learn more about the update_many() method, see the Update Documents section of the Modify Documents guide.

This example updates a document in the restaurants collection of the sample_restaurants database.

The following code adds the near_me field to documents in which the value of the address.street field is "Sullivan Street" and the borough field is "Manhattan".

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use bson::Document;
#[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! {
"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(())
}
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).run()?;
println!("Updated documents: {}", res.modified_count);
Ok(())
}

Back

Update a Document

Next

Replace a Document