Docs Menu
Docs Home
/ /

複合演算子

このガイドでは、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 つのドキュメントを検索して置換

このガイドには、次のセクションが含まれています。

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()メソッドを呼び出します。

オプションで、 FineOneAndDeleteOptionsインスタンスをパラメータとして渡すことで、 find_one_and_delete()メソッドの動作を変更できます。 各設定でデフォルト値を使用するには、オプション パラメータに値Noneを指定します。

次の表では、 FineOneAndDeleteOptionsで利用できるオプションについて説明しています。

オプション
説明

max_time

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: None

sort

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: Document
Default: None

write_concern

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

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

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: Hint
Default: None

let_vars

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

comment

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: Bson
Default: None

Rust ドライバーは、 FindOneAndDeleteOptionsインスタンスを作成するためのビルダ設計パターンを実装します。 タイプのbuilder()メソッドを使用して、オプション ビルダー関数を 1 つずつ連鎖させてオプション インスタンスを構築できます。

次のコードは、 FindOneAndDeleteOptionsインスタンスを構築し、それをfind_one_and_delete()メソッドに渡す方法を示しています。

let opts = FindOneAndDeleteOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_delete(filter, opts).await?;

次の例では、 find_one_and_delete()メソッドを使用して、 ageフィールドの値が10以下の最初のドキュメントを検索して削除します。

let filter = doc! { "age": doc! { "$lte": 10 } };
let res = my_coll.find_one_and_delete(filter, None).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()メソッドを呼び出します。

オプションで、 FindOneAndUpdateOptionsインスタンスをパラメータとして渡すことで、 find_one_and_update()メソッドの動作を変更できます。 各設定でデフォルト値を使用するには、オプション パラメータに値Noneを指定します。

次の表では、 FineOneAndDeleteOptionsで利用できるオプションについて説明しています。

オプション
説明

array_filters

The set of filters specifying the array elements to which the update applies.

Type: Vec<Document>

bypass_document_validation

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: bool
Default: false

max_time

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: None

return_document

If Before, the operation returns the document before the update. If After, the operation returns the updated document.

Type: ReturnDocument
Default: ReturnDocument::Before

sort

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: Document
Default: None

upsert

If true, the operation inserts a document if no documents match the query filter.

Type: bool
Default: false

write_concern

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

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

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: Hint
Default: None

let_vars

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

comment

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: Bson
Default: None

Rust ドライバーは、 FindOneAndUpdateOptionsインスタンスを作成するためのビルダ設計パターンを実装します。 タイプのbuilder()メソッドを使用して、オプション ビルダー メソッドを 1 つずつ連鎖させてオプション インスタンスを構築できます。

次のコードは、 FindOneAndUpdateOptionsインスタンスを構築し、それをfind_one_and_update()メソッドに渡す方法を示しています。

let opts = FindOneAndUpdateOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_update(filter, update, opts).await?;

以下の例では、次のパラメータを使用してfind_one_and_update()メソッドを呼び出す方法を示しています。

  • schoolの値が"Aurora High School"であるドキュメントに一致するクエリフィルター

  • schoolフィールドを"Durango High School"に設定し、 ageフィールドを1ずつ増加させる更新ドキュメント

  • 更新にドキュメントを返すFindOneAndUpdateOptionsインスタンス

let filter = doc! { "school": "Aurora High School" };
let update =
doc! { "$set": doc! { "school": "Durango High School" },
"$inc": doc! { "age": 1 } };
let opts = FindOneAndUpdateOptions::builder()
.return_document(Some(ReturnDocument::After))
.build();
let res = my_coll.find_one_and_update(filter, update, opts).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()メソッドを呼び出します。

オプションで、 FindOneAndReplaceOptionsインスタンスをパラメータとして渡すことで、 find_one_and_replace()メソッドの動作を変更できます。 各設定でデフォルト値を使用するには、オプション パラメータに値Noneを指定します。

次の表では、 FindOneAndReplaceOptionsで利用できるオプションについて説明しています。

オプション
説明

bypass_document_validation

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: bool
Default: false

max_time

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: None

return_document

If Before, the operation returns the document before the update. If After, the operation returns the updated document.

Type: ReturnDocument
Default: ReturnDocument::Before

sort

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: Document
Default: None

upsert

If true, the operation inserts a document if no documents match the query filter.

Type: bool
Default: false

write_concern

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

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

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: Hint
Default: None

let_vars

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

comment

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: Bson
Default: None

Rust ドライバーは、 FindOneAndReplaceOptionsインスタンスを作成するためのビルダ設計パターンを実装します。 タイプのbuilder()メソッドを使用して、オプション ビルダー関数を 1 つずつ連鎖させてオプション インスタンスを構築できます。

次のコードは、 FindOneAndReplaceOptionsインスタンスを構築し、それをfind_one_and_replace()メソッドに渡す方法を示しています。

let opts = FindOneAndReplaceOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_replace(filter, replacement, opts).await?;

以下の例では、次のパラメータを使用してfind_one_and_replace()メソッドを呼び出す方法を示しています。

  • "Johnson" nameの値に string が含まれるドキュメントに一致するクエリフィルター

  • 新しい学生を説明する置換ドキュメント

  • FindOneAndReplaceOptionsname置換後にドキュメントを返し、出力のschool フィールドと フィールドのみをプロジェクションする インスタンス

let filter = doc! { "name": doc! { "$regex": "Johnson" } };
let replacement =
doc! { "name": "Toby Fletcher",
"age": 14,
"school": "Durango High School" };
let opts = FindOneAndReplaceOptions::builder()
.return_document(Some(ReturnDocument::After))
.projection(doc! { "name": 1, "school": 1, "_id": 0 })
.build();
let res = my_coll.find_one_and_replace(filter, replacement, opts).await?;
println!("Document after replacement:\n{:?}", res);
Document after replacement:
Some(Document({"name": String("Toby Fletcher"), "school":
String("Durango High School")}))

このガイドの操作の詳細については、次のドキュメントを参照してください。

このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。

戻る

一括操作

項目一覧