Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Java Reactive Streams ドライバー
/

一括書き込み操作

このガイドでは、一括書込み操作を使用して、1 つのデータベース呼び出しで複数の書込み操作を実行する方法を学習できます。

コレクションにドキュメントを挿入 し、複数の他のドキュメントを更新してから、ドキュメントを削除するシナリオを考えてみましょう。 個々のメソッドを使用する場合、各操作には独自のデータベース呼び出しが必要です。 このガイドでは、一括書き込み操作を使用してデータベースへの呼び出し回数を減らす方法について説明します。

このガイドの例では、 Atlasサンプルデータセット sample_restaurants.restaurantsコレクションを使用します。 MongoDB Atlasクラスターを無料で作成し、サンプルデータセットをロードする方法については、「 を使い始める 」チュートリアルを参照してください。

重要

プロジェクトリ アクター ライブラリ

このガイドでは、プロジェクト Reactive ライブラリを使用して、 Java Reactive Streams ドライバー メソッドによって返されたPublisherインスタンスを消費します。 Project Reactive ライブラリとその使用方法の詳細については、「 使用 開始 」を 参照してください。 (Reactor ドキュメントの参照)。このガイドでは Project React ライブラリ メソッドをどのように使用しているかについて詳しくは、「 MongoDBへのデータの書込み」ガイドを参照してください。

実行する書込み操作ごとに、次のいずれかのクラスのインスタンスを作成します。

  • InsertOneModel

  • UpdateOneModel

  • UpdateManyModel

  • ReplaceOneModel

  • DeleteOneModel

  • DeleteManyModel

次に、これらのインスタンスのリストをbulkWrite()メソッドに渡します。

次のセクションでは、前述のクラスのインスタンスを作成して使用する方法を示します。

挿入操作を実行するには、 InsertOneModelのインスタンスを作成し、挿入するドキュメントを渡します。

次の例では、 InsertOneModelのインスタンスを作成しています。

InsertOneModel<Document> operation = new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches"));

複数のドキュメントを挿入するには、ドキュメントごとにInsertOneModelのインスタンスを作成します。

ドキュメントを更新するには、 UpdateOneModelのインスタンスを作成し、次の引数を渡します。

  • コレクション内のドキュメントをマッチングするために使用される基準を指定するクエリフィルター

  • 実行する更新操作。 更新操作の詳細については、 MongoDB Serverマニュアルの「フィールド更新演算子」ガイドを参照してください。

UpdateOneModel はクエリフィルターに一致する最初のドキュメントを更新します。

次の例では、 UpdateOneModelのインスタンスを作成しています。

UpdateOneModel<Document> operation = new UpdateOneModel<>(
eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads"));

複数のドキュメントを更新するには、 UpdateManyModelのインスタンスを作成し、同じ引数で渡します。 UpdateManyModelは、クエリフィルターに一致するすべてのドキュメントを更新します。

次の例では、 UpdateManyModelのインスタンスを作成しています。

UpdateManyModel<Document> operation = new UpdateManyModel<>(
eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads"));

置換操作すると、 _idフィールド以外の、指定されたドキュメントのすべてのフィールドと値が削除され、新しいフィールドと値に置き換えられます。 置換操作を実行するには、 ReplaceOneModelのインスタンスを作成し、クエリフィルターと、一致するドキュメントに保存するフィールドと値を渡します。

次の例では、 ReplaceOneModelのインスタンスを作成しています。

ReplaceOneModel<Document> operation = new ReplaceOneModel<>(
eq("name", "Original Pizza"),
new Document("name", "Mongo's Pizza")
.append("borough", "Manhattan"));

複数のドキュメントを置き換えるには、ドキュメントごとにReplaceOneModelのインスタンスを作成します。

ドキュメントを削除するには、 DeleteOneModelのインスタンスを作成し、削除するドキュメントを指定するクエリフィルターを渡します。 DeleteOneModelは、クエリフィルターに一致する最初のドキュメントのみを削除します。

次の例では、 DeleteOneModelのインスタンスを作成しています。

DeleteOneModel<Document> operation = new DeleteOneModel<>(
eq("restaurant_id", "5678"));

複数のドキュメントを削除するには、 DeleteManyModelのインスタンスを作成し、削除するドキュメントを指定するクエリフィルターを渡します。 DeleteManyModelは、クエリフィルターに一致するすべてのドキュメントを削除します。

次の例では、 DeleteManyModelのインスタンスを作成しています。

DeleteManyModel<Document> operation = new DeleteManyModel<>(
eq("name", "Mongo's Deli"));

実行する操作ごとにクラス インスタンスを定義したら、これらのインスタンスのリストをbulkWrite()メソッドに渡します。 デフォルトでは、メソッドはリストで定義された順序で操作を実行します。

次の例では、 bulkWrite()メソッドを使用して複数の書込み操作を実行します。

Publisher<BulkWriteResult> bulkWritePublisher = restaurants.bulkWrite(
Arrays.asList(new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Manhattan")
.append("restaurant_id", "1234")),
new InsertOneModel<>(new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Brooklyn")
.append("restaurant_id", "5678")),
new UpdateManyModel<>(eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads")),
new DeleteOneModel<>(eq("restaurant_id", "1234"))));
BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block();
System.out.println(bulkResult.toString());
AcknowledgedBulkWriteResult{insertedCount=2, matchedCount=2, removedCount=1, modifiedCount=2, upserts=[], inserts=[BulkWriteInsert{index=0, id=BsonObjectId{value=66a7e0a6c08025218b657208}}, BulkWriteInsert{index=1, id=BsonObjectId{value=66a7e0a6c08025218b657209}}]}

いずれかの書込み操作が失敗した場合、 Java Reactive Streams ドライバーはMongoBulkWriteExceptionをシグナルし、それ以上の個々の操作を実行しません。 MongoBulkWriteExceptionにはMongoBulkWriteException.getWriteErrors()メソッドを使用してアクセスできるBulkWriteErrorが含まれており、個々の障害の詳細が提供されます。

注意

Java Reactive Streams ドライバーが 一括操作を実行する場合、操作が実行中されているコレクションのwriteConcernを使用します。 ドライバーは、実行順序に関係なく、すべての操作を試行した後にすべての書込み保証 ( 書込み保証 (write concern) ) エラーを報告します。

BulkWriteOptionsクラスには、 bulkWrite()メソッドの動作を変更するメソッドが含まれています。 BulkWriteOptionsクラスを使用するには、クラスの新しいインスタンスを作成し、そのメソッドの 1 つ以上を呼び出して 書込み操作を変更します。 これらのメソッド呼び出しを連鎖させることができます。 書込み操作の動作を変更するには、クラスインスタンスをbulkWrite()メソッドの最後の引数として渡します。

書き込みメソッドを変更するには、 BulkWriteOptionsクラスの次のメソッドを使用します。 すべてのメソッドは任意です。

方式
説明

bypassDocumentValidation(Boolean bypassDocumentValidation)

Specifies whether the bulk write operation bypasses document validation. This lets you perform write operations on documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.

comment(Bson comment)

Attaches a Bson comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

comment(String comment)

Attaches a String comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

let(Bson variables)

Specifies a map of parameter names and values. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.

ordered(Boolean ordered)

If set to True, the driver performs the individual operations in the order provided. If an individual operation fails, the driver will not execute any subsequent individual operations.
Defaults to True.

次の例では、前の例からbulkWrite()メソッドを呼び出しますが、 orderedオプションをFalseに設定します。

Publisher<BulkWriteResult> bulkWritePublisher = restaurants.bulkWrite(
Arrays.asList(new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Manhattan")
.append("restaurant_id", "1234")),
new InsertOneModel<>(new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Brooklyn")
.append("restaurant_id", "5678")),
new UpdateManyModel<>(eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads")),
new DeleteOneModel<>(eq("restaurant_id", "1234"))),
new BulkWriteOptions().ordered(false));
BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block();
System.out.println(bulkResult.toString());
AcknowledgedBulkWriteResult{insertedCount=2, matchedCount=2, removedCount=1, modifiedCount=2, upserts=[], inserts=[BulkWriteInsert{index=0, id=BsonObjectId{value=66a7e03cce430c5854b6caf9}}, BulkWriteInsert{index=1, id=BsonObjectId{value=66a7e03cce430c5854b6cafa}}]}

順序付けなし一括書き込み 内のいずれかの書込み操作が失敗した場合、 Java Reactive Streams ドライバーはすべての操作を試行した後にのみエラーを報告します。

注意

順序なしの一括操作では、実行順序は保証されません。 この順序は、ランタイムを最適化するために一覧表示する方法とは異なる場合があります。

個々の書込み操作を実行する方法については、次のガイドを参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

削除

項目一覧