コレクション内のドキュメントを更新するには、 Collectionインスタンスで update_one() メソッドを呼び出します。
次のパラメータをupdate_one()メソッドに渡します。
- 一致する基準を指定するクエリフィルター 
- ドキュメントの更新 。最初に一致したドキュメントに対する更新を指定します。 
update_one() メソッドは、変更されたドキュメントの数など、 更新操作の結果に関する情報を含む UpdateResult タイプを返します。
update_one()メソッドの詳細については、ドキュメントの修正 ガイドの「 ドキュメントのアップデート 」セクションを参照してください。
例
この例では、 sample_restaurantsデータベースの restaurantsコレクション内のドキュメントを更新します。 update_one() メソッドは、nameフィールドの値が "Spice Market" である最初のドキュメントに priceフィールドを追加します。
restaurantsコレクション内のドキュメントには、Document 型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。
- <Document>:コレクションドキュメントはBSONドキュメントとしてアクセスします
- <Restaurant>: コードの上部で定義された- Restaurant構造体のインスタンスとしてコレクションドキュメントにアクセスします
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
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