コレクション内のドキュメントを更新するには、 Collectionインスタンスで update_one() メソッドを呼び出します。
次のパラメータをupdate_one()メソッドに渡します。
一致する基準を指定するクエリフィルター
ドキュメントの更新 。最初に一致したドキュメントに対する更新を指定します。
update_one() メソッドは、変更されたドキュメントの数など、 更新操作の結果に関する情報を含む UpdateResult タイプを返します。
update_one()メソッドの詳細については、ドキュメントの修正 ガイドの「 ドキュメントのアップデート 」セクションを参照してください。
例
この例では、 sample_restaurantsデータベースのrestaurantsコレクション内のドキュメントをアップデートします。
次のコードでは、 nameフィールドの値が"Spice Market"であるドキュメントにpriceフィールドを追加します。 MongoDB はクエリフィルターに一致する最初のドキュメントを更新します。
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::{ Document, doc }, Client, Collection }; 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, None).await?; println!("Updated documents: {}", res.modified_count); Ok(()) }
Updated documents: 1
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, None)?; println!("Updated documents: {}", res.modified_count); Ok(()) }
Updated documents: 1