ドキュメントの置き換え
コレクション内のドキュメントを置き換えるには、 replace_one() メソッドを呼び出しますCollection
インスタンスのメソッドです。
次のパラメータをreplace_one()
メソッドに渡します。
一致する基準を指定するクエリフィルター
最初に一致したドキュメントを置き換えるフィールドと値を含む 置換ドキュメント
replace_one()
メソッドは UpdateResult を返します 変更されたドキュメントの数など、置換操作の結果に関する情報を含むタイプ。
replace_one()
メソッドの詳細については、 ドキュメントの修正 ガイドの「 ドキュメントの置き換え 」セクションを参照してください。
例
この例では、 sample_restaurants
データベースのrestaurants
コレクション内のドキュメントを置き換えます。 この例では、コレクション内のドキュメントをモデル化するために、 name
、 borough
、 cuisine
フィールドを持つRestaurant
構造体を使用します。
次のコードは、 name
フィールドの値が"Landmark Coffee Shop"
であるドキュメントを新しいドキュメントに置き換えます。 MongoDB は、クエリフィルターに一致する最初のドキュメントを置き換えます。
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::doc, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "name": "Landmark Coffee Shop" }; let replacement = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; let res = my_coll.replace_one(filter, replacement).await?; println!("Replaced documents: {}", res.modified_count); Ok(()) }
use std::env; use mongodb::{ bson::doc, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "name": "Landmark Coffee Shop" }; let replacement = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; let res = my_coll.replace_one(filter, replacement).run()?; println!("Replaced documents: {}", res.modified_count); Ok(()) }