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.
Example
This example updates a document in the restaurants collection of
the sample_restaurants database. The update_one() method adds
the price field to the first document in which the value of the name
field is "Spice Market".
You can access the documents in the restaurants collection as instances
of the Document type or a custom data type. To specify which data type represents
the collection's data, replace the <T> type parameter on the highlighted
line with one of the following values:
<Document>: Accesses collection documents as BSON documents<Restaurant>: Accesses collection documents as instances of theRestaurantstruct, defined at the top of the code
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
use std::env; use mongodb::{ bson::{ Document, doc }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, price: String, } 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! { "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(()) }
Updated documents: 1
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, price: String, } 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! { "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(()) }
Updated documents: 1