Overview
このガイドでは、Rust ドライバーを使用して複合操作を実行する方法を説明します。
複合操作は、読み取り操作と書込み (write) 操作の機能を 1 つのアトミックアクションに結合します。 If you perform a read operation and a write operation in sequence, someone might change your target document between the operations, leading to unexpected results. 複合操作を実行する場合、MongoDB は操作が完了するまで変更しているドキュメントに書込みロック (write lock) を適用して中間データの変更を防ぎます。
ドライバーを使用して次の複合操作を実行できます。
1 つのドキュメントを検索して削除
1 つのドキュメントを検索して更新
1 つのドキュメントを検索して置換
このガイドには、次のセクションが含まれています。
例のサンプル データ では、複合操作の例で使用されるサンプル データが
「ドキュメントの検索と削除」では、1 回の操作でドキュメントを検索して削除する方法について説明します
ドキュメントの検索と更新では、1 回の操作でドキュメントを検索して更新する方法について説明します
「ドキュメントの検索と置換」では、1 回の操作でドキュメントを検索して置換する方法について説明します
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します
Tip
一度に複数のドキュメントに対してアトミックな読み取りおよび書込み操作を実行する方法については、 トランザクションガイドを参照してください。
サンプルデータの例
このガイドの例では、次のサンプル ドキュメントを使用します。 各ドキュメントは学生を表し、その名前の詳細と所属するデータベースに関する情報が含まれています。
{ "name": "Alex Johnson", "age": 8, "school": "Lakeside Elementary" }, { "name": "Samara Khan", "age": 11, "school": "Rolling Hills Middle School" }, { "name": "Ben Joseph", "age": 16, "school": "Aurora High School" }, { "name": "Deanna Porowski", "age": 10, "school": "Lakeside Elementary" }
ドキュメントの検索と削除
find_one_and_delete()メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索して削除します。 ドキュメントがフィルタ条件に一致する場合、メソッドはSomeタイプを返します。 一致するドキュメントがない場合は、 Noneタイプが返されます。
注意
ドキュメントの検索と削除の間に他の操作を実行する場合は、 find_one()メソッドを呼び出し、その後にdelete_one()メソッドを呼び出します。
検索と削除の動作を変更する
オプションで、オプション ビルダー メソッドをfind_one_and_delete()に連鎖させることで、 find_one_and_delete()メソッドの動作を変更できます。 これらのビルダー メソッドはFindOneAndDeleteOptions構造体フィールドを設定します。
次の表では、 FindOneAndDeleteOptionsで利用できるオプションについて説明しています。
オプション | 説明 |
|---|---|
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: DocumentDefault: None |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: DocumentDefault: None |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: HintDefault: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
注意
設定オプション
オプション ビルダのメソッドをfind_one_and_delete()メソッド呼び出しに直接連鎖させることで、 FindOneAndDeleteOptionsフィールドを設定できます。 以前のバージョンのドライバーを使用している場合は、オプション ビルダー メソッドをbuilder()メソッドに連結してFindOneAndDeleteOptionsインスタンスを構築する必要があります。 次に、オプション インスタンスをパラメーターとしてfind_one_and_delete()に渡します。
次のコードは、 comment()メソッドをfind_one_and_delete()メソッドに連結してcommentフィールドを設定する方法を示しています。
let res = my_coll.find_one_and_delete(filter) .comment(bson!("hello")) .await?;
検索と削除の例
次の例では、 find_one_and_delete()メソッドを使用して、 ageフィールドの値が10以下の最初のドキュメントを検索して削除します。
let filter = doc! { "age": doc! { "$lte": 10 } }; let res = my_coll.find_one_and_delete(filter).await?; println!("Deleted document:\n{:?}", res);
Deleted document: Some(Document({"_id": ObjectId("..."), "name": String("Deanna Porowski"), "age": Int32(10), "school": String("Lakeside Elementary")}))
ドキュメントの検索と更新
find_one_and_update()メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索してアップデートします。 この操作では、更新ドキュメントで指定した仕様に基づいてドキュメントが更新されます。 ドキュメントがフィルタ条件に一致する場合、メソッドはSomeタイプを返します。 一致するドキュメントがない場合は、 Noneタイプが返されます。
注意
ドキュメントの検索と更新の間に他の操作を実行する場合は、 find_one()メソッドを呼び出し、その後にupdate_one()メソッドを呼び出します。
検索と更新の動作を変更する
オプションで、オプション ビルダー メソッドをfind_one_and_update()に連鎖させることで、 find_one_and_update()メソッドの動作を変更できます。 これらのビルダー メソッドはFindOneAndUpdateOptions構造体フィールドを設定します。
次の表では、 FindOneAndUpdateOptionsで利用できるオプションについて説明しています。
オプション | 説明 |
|---|---|
| The set of filters specifying the array elements to which the
update applies. Type: Vec<Document> |
| If true, allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
Schema Validation in the Server manual.Type: boolDefault: false |
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: DocumentDefault: None |
| If Before, the operation returns the document before the
update. If After, the operation returns the updated document.Type: ReturnDocumentDefault: ReturnDocument::Before |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: DocumentDefault: None |
| If true, the operation inserts a document if no documents match
the query filter. Type: boolDefault: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: HintDefault: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
次のコードは、 comment()メソッドをfind_one_and_update()メソッドに連結してcommentフィールドを設定する方法を示しています。
let res = my_coll.find_one_and_update(filter, update) .comment(bson!("hello")) .await?;
検索と更新の例
この例では、次のアクションを実行する方法を示しています。
find_one_and_update()メソッドを呼び出すschoolの値が"Aurora High School"であるドキュメントに一致するクエリフィルターをfind_one_and_update()に渡すアップデート ドキュメントを
find_one_and_update()に渡します。これで、schoolフィールドを"Durango High School"に設定し、ageフィールドを1ずつ増加させます更新後に一致したドキュメントを返すには、
return_document()メソッドをfind_one_and_update()にチェーンします
let filter = doc! { "school": "Aurora High School" }; let update = doc! { "$set": doc! { "school": "Durango High School" }, "$inc": doc! { "age": 1 } }; let res = my_coll.find_one_and_update(filter, update) .return_document(ReturnDocument::After) .await?; println!("Updated document:\n{:?}", res);
Updated document: Some(Document({"_id": ObjectId("..."), "name": String("Ben Joseph"), "age": Int32(17), "school": String("Durango High School")}))
ドキュメントの検索と置換
find_one_and_replace()メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索して置き換えます。 この操作により、 _idフィールドを除くドキュメントのすべてのフィールドが、指定したフィールドと値に置き換えられます。 ドキュメントがフィルタ条件に一致する場合、メソッドはSome型を返します。 一致するドキュメントがない場合は、 Noneタイプが返されます。
注意
ドキュメントの検索と置換の間に他の操作を実行する場合は、 find_one()メソッド、その後にreplace_one()メソッドを呼び出します。
検索と置換の動作を変更する
オプションで、オプション ビルダー メソッドをfind_one_and_replace()に連鎖させることで、 find_one_and_replace()メソッドの動作を変更できます。 これらのビルダー メソッドはFindOneAndReplaceOptions構造体フィールドを設定します。
次の表では、 FindOneAndReplaceOptionsで利用できるオプションについて説明しています。
オプション | 説明 |
|---|---|
| If true, allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
Schema Validation in the Server manual.Type: boolDefault: false |
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: DocumentDefault: None |
| If Before, the operation returns the document before the
update. If After, the operation returns the updated document.Type: ReturnDocumentDefault: ReturnDocument::Before |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: DocumentDefault: None |
| If true, the operation inserts a document if no documents match
the query filter. Type: boolDefault: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: HintDefault: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
次のコードは、 comment()メソッドをfind_one_and_replace()メソッドに連結してcommentフィールドを設定する方法を示しています。
let res = my_coll.find_one_and_replace(filter, replacement) .comment(bson!("hello")) .await?;
検索と置換の例
この例では、次のアクションを実行します。
find_one_and_replace()メソッドを呼び出しますnameの値に string が含まれるドキュメントに一致するクエリフィルターをfind_one_and_replace()"Johnson"渡します新しい学生を説明する置換ドキュメントを
find_one_and_replace()に渡します置換後にドキュメントを返すには、
return_document()メソッドをfind_one_and_replace()にチェーンしますメソッドを出力の フィールドと フィールドにチェーンします
projection()find_one_and_replace()``to project only the ``nameschool
let filter = doc! { "name": doc! { "$regex": "Johnson" } }; let replacement = doc! { "name": "Toby Fletcher", "age": 14, "school": "Durango High School" }; let res = my_coll.find_one_and_replace(filter, replacement) .return_document(ReturnDocument::After) .projection(doc! { "name": 1, "school": 1, "_id": 0 }) .await?; println!("Document after replacement:\n{:?}", res);
Document after replacement: Some(Document({"name": String("Toby Fletcher"), "school": String("Durango High School")}))
詳細情報
このガイドの操作の詳細については、次のドキュメントを参照してください。
API ドキュメント
このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。