Docs Menu
Docs Home
/ / /
Rust Driver
/

Update a Document

You can update a document in a collection by calling the update_one() method on a Collection instance.

Pass the following parameters to the update_one() method:

  • Query filter, which specifies the criteria to match

  • Update document, which specifies the updates to make to the first matched document

The update_one() 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_one() 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 price field to a document in which the value of the name field is "Spice Market". MongoDB updates the first document that matches the query filter.

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

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).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! { "name": "Spice Market" };
let update = doc! { "$set": doc! {"price": "$$$"} };
let res = my_coll.update_one(filter, update).run()?;
println!("Updated documents: {}", res.modified_count);
Ok(())
}

Back

Insert Multiple Documents

Next

Update Multiple Documents