一括書き込み操作
Overview
このガイドでは、一括書込み操作を使用して、1 つのデータベース呼び出しで複数の書込み操作を実行する方法を学習できます。
ドキュメントを挿入し、複数の他のドキュメントを更新してから、ドキュメント を削除するシナリオを考えてみましょう。 個々のメソッドを使用する場合、各操作には独自のデータベース呼び出しが必要です。
一括書き込み操作 を使用すると、より少ないデータベース呼び出しで複数の書き込み操作を実行できます。 次のレベルで一括書き込み操作を実行できます。
クライアント :アプリケーションがMongoDB Serverバージョン 8.0 以降に接続している場合は、
MongoDB\Client::bulkWrite()
メソッドを使用して、同じクラスター内の複数のコレクションとデータベースに対して一括書込み操作を実行できます。このメソッドは、1 回のデータベース呼び出しですべての書き込み操作を実行します。この機能の詳細については、Mongo.bulkWrite()参照( MongoDB Serverマニュアル)コレクション :
MongoDB\Collection::bulkWrite()
メソッドを使用して、単一のコレクションに対して一括書き込み操作を実行できます。このメソッドは、書込み (write)操作の各タイプに対してデータベースを呼び出します。例、 メソッドは 1 回の呼び出しで複数のアップデート操作を実行できますが、 挿入操作と 置換操作 のためにデータベースに対して 2 回個別の呼び出しを行います。
サンプル データ
このガイドの例では、sample_restaurants.restaurants
sample_mflix.movies
Atlasサンプルデータセット の コレクションと コレクションを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイド を参照してください。
クライアント一括書込み (write)
PHPライブラリ v2.1 を使用しており、 MongoDB Server 8.0 以降を実行中配置に接続する場合、MongoDB\Client::bulkWrite()
メソッドを使用して、同じクラスター内の複数のデータベースとコレクションに書込むことができます。このメソッドは、1 回の呼び出しですべての書き込み操作を実行します。
まず、MongoDB\ClientBulkWrite
ビルダを使用して、実行する書込み操作を指定するBulkWriteCommandインスタンスを作成します。次のコードは、createWithCollection()
メソッドを使用して、MongoDB\Collection
インスタンスから ClientBulkWrite
インスタンスを作成する方法を示しています。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
次に、ClientBulkWrite
インスタンスで次の書き込みメソッドの 1 つ以上を呼び出して、 一括書き込み操作を構築します。
deleteOne()
deleteMany()
insertOne()
replaceOne()
updateOne()
updateMany()
後続の書き込み操作で別の名前空間を選択するには、次のコードに示すように、ClientBulkWrite
インスタンスで withCollection()
メソッドを呼び出します。
$movieCollection = $client->sample_mflix->movies; $bulkWrite = $bulkWrite->withCollection($movieCollection);
次のセクションでは、ClientBulkWrite
クラスの作成と使用を使用して、一括書き込みで書込み操作を指定する方法を示します。「 一括操作の実行 」セクションでは、ClientBulkWrite
オブジェクトを bulkWrite()
メソッドに渡して 一括操作を実行する方法が説明されています。
挿入操作
挿入操作を指定するには、ClientBulkWrite
インスタンスで insertOne()
メソッドを呼び出します。
次の例では、sample_restaurants.restaurants
コレクションと sample_mflix.movies
コレクションへのドキュメントの挿入を指定しています。
$restaurantCollection = $client->sample_restaurants->restaurants; $movieCollection = $client->sample_mflix->movies; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); $bulkWrite = $bulkWrite->withCollection($movieCollection); $bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]);
アップデート操作
最初に一致するドキュメントのアップデート操作を指定するには、ClientBulkWrite
インスタンスで updateOne()
メソッドを呼び出します。
次の例では、sample_restaurants.restaurants
コレクション内の name
値が 'Dandelion Bakery'
である最初のドキュメントに対する $set
アップデートを指定します。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->updateOne( ['name' => 'Dandelion Bakery'], ['$set' => ['grade' => 'B+']], ['upsert' => true], );
複数のドキュメントを更新するには、updateMany()
メソッドを呼び出します。指定された操作は、 クエリフィルターに一致するすべてのドキュメントを更新します。
次の例では、name
の値が 'Starbucks'
である、sample_restaurants.restaurants
コレクション内の一致するすべてのドキュメントに対する $set
アップデートを指定します。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->updateMany( ['name' => 'Starbucks'], ['$set' => ['cuisine' => 'Coffee (Chain)']], );
置換操作
最初に一致するドキュメントで置換操作を指定するには、ClientBulkWrite
インスタンスで replaceOne()
メソッドを呼び出します。
次の例では、name
の値が 'Dandelion Bakery'
である sample_restaurants.restaurants
コレクション内の最初のドキュメントに対する置換操作を指定します。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->replaceOne( ['name' => 'Dandelion Bakery'], ['name' => 'Flower Patisserie', 'cuisine' => 'Bakery & Cafe'], );
削除操作
最初に一致するドキュメントの削除操作を指定するには、ClientBulkWrite
インスタンスで deleteOne()
メソッドを呼び出します。
次の例では、sample_restaurants.restaurants
コレクション内の borough
値が 'Queens'
である最初のドキュメントの削除を指定します。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->deleteOne( ['borough' => 'Queens'], );
複数のドキュメントを削除するには、deleteMany()
メソッドを呼び出します。指定された操作は、クエリフィルターに一致するすべてのドキュメントを削除します。
次の例では、連続する 2 文字の 'p'
文字を含む name
値を持つ sample_restaurants.restaurants
コレクション内のすべてのドキュメントの削除を指定します。
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->deleteMany( ['name' => ['$regex' => 'p{2,}']], );
一括操作の実行
書込み操作を指定するために ClientBulkWrite
インスタンスを作成したら、それを MongoDB\Client::bulkWrite()
メソッドに渡します。デフォルトでは 、これらのメソッドは ClientBulkWrite
の構築時に定義した順序で操作を実行します。
次のコードは、bulkWrite()
メソッドを使用して複数の名前空間で一括書き込み操作を実行する方法を示しています。
$restaurantCollection = $client->sample_restaurants->restaurants; $movieCollection = $client->sample_mflix->movies; // Creates the bulk write command and sets the target namespace. $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); // Specifies insertion of one document. $bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); // Specifies a `$set` update to one document with the upsert option // enabled. $bulkWrite->updateOne( ['name' => 'Dandelion Bakery'], ['$set' => ['grade' => 'B+']], ['upsert' => true], ); // Changes the target namespace. $bulkWrite = $bulkWrite->withCollection($movieCollection); // Specifies insertion of one document. $bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]); // Specifies deletion of documents in which `title` has two consective // 'd' characters. $bulkWrite->deleteMany( ['title' => ['$regex' => 'd{2,}']], ); // Specifies replacement of one document. $bulkWrite->replaceOne( ['runtime' => ['$gte' => 200]], ['title' => 'Seven Samurai', 'runtime' => 203], ); // Performs the bulk write operation. $result = $client->bulkWrite($bulkWrite); // Prints a summary of results. echo 'Inserted documents: ', $result->getInsertedCount(), PHP_EOL; echo 'Modified documents: ', $result->getModifiedCount(), PHP_EOL; echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Inserted documents: 2 Modified documents: 2 Deleted documents: 200
一括書き込みをカスタマイズする
クライアント一括書き込み操作の動作を変更するには、パラメーターとしてオプション値を指定する配列を ClientBulkWrite
コンストラクターに渡します。次の表では、 配列に設定できるオプションについて説明しています。
オプション | 説明 |
---|---|
| Specifies whether the operation bypasses document validation. This lets you
modify 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. The default is false . |
| Attaches a comment to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
| Specifies a document with a list of values to improve operation readability.
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. |
| If set to true : When a single write fails, the operation stops without
performing the remaining writes and throws an exception.If set to false : When a single write fails, the operation continues to
attempt the remaining write operations, if any, then throws an exception.The default is true . |
| Specifies whether to return verbose results. The default is false . |
次の例では、ClientBulkWrite
インスタンスを作成し、ordered
オプションを false
に設定します。
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection( $restaurantCollection, ['ordered' => false] );
注意
順序なし動作
順序なしの一括操作では、実行順序は保証されません。この順序は、ランタイムを最適化するために一覧表示する方法とは異なる場合があります。順序なしの一括書き込みで次の書き込み操作を指定するとします。
$bulkWrite->insertOne(['_id' => 4045, 'title' => 'The Green Ray']); $bulkWrite->deleteOne(['_id' => 4045]);
ライブラリは最初にいずれかの操作を実行する可能性があるため、結果には削除されたドキュメントが 1 つ表示される場合もあります。
また、 bulkWrite()
メソッドを呼び出すときにオプションを渡して、操作に使用するクライアントセッションまたは書込み保証 (write concern)を指定することもできます。
戻り値
MongoDB\Client::bulkWrite()
メソッドは MongoDB\BulkWriteCommandResult
オブジェクトを返します。このクラスには、次のメソッドが含まれています。
方式 | 説明 |
---|---|
| Returns the total number of documents inserted by all
insert operations in the bulk write command. |
| Returns the total number of documents matched by all
update and replace operations in the bulk write command. |
| Returns the total number of documents modified by all update
and replace operations in the bulk write command. |
| Returns the total number of documents upserted by all update
and replace operations in the bulk write command. |
| Return the total number of documents deleted by all delete
operations in the bulk write command. |
| Returns a map of results of each successful insert operation. Each
operation is represented by an integer key, which contains a
document with information corresponding to the operation such
as the inserted _id value. |
| Returns a map of results of each successful update operation. Each
operation is represented by an integer key, which contains a
document with information corresponding to the operation. |
| Returns a map of results of each successful delete operation.
Each operation is represented by an integer key, which contains
a document with information corresponding to the operation. |
| Returns a boolean indicating whether the server acknowledged
the bulk operation. |
コレクションの一括書込み (write)
一括書込み操作を実行するには、書込み操作の配列を MongoDB\Collection::bulkWrite()
メソッドに渡します。書込み操作を指定するには、次の構文を使用します。
[ [ 'deleteMany' => [ $filter ] ], [ 'deleteOne' => [ $filter ] ], [ 'insertOne' => [ $document ] ], [ 'replaceOne' => [ $filter, $replacement, $options ] ], [ 'updateMany' => [ $filter, $update, $options ] ], [ 'updateOne' => [ $filter, $update, $options ] ], ]
Tip
削除、挿入、置換、および更新操作の詳細については、 「 MongoDBへのデータの書込み 」セクションのガイドを参照してください。
bulkWrite()
メソッドを呼び出すと、ライブラリは 配列で指定した順序で書込み操作を自動的に実行します。書き込み操作を任意の順序で実行するよう bulkWrite()
に指示する方法については、一括書き込み操作のカスタマイズ セクションを参照してください。
例
この例では、 restaurants
コレクションに対して次の書き込み操作を実行します。
挿入操作は、
name
値が'Mongo's Deli'
であるドキュメントを挿入しますname
値が'Mongo's Deli'
であるドキュメントのcuisine
フィールドを更新する更新操作borough
値が'Manhattan'
であるすべてのドキュメントを削除する削除操作
$restaurantCollection = $client->sample_restaurants->restaurants; $result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ ['name' => 'Mongo\'s Deli'], ['cuisine' => 'Sandwiches'], ['borough' => 'Manhattan'], ['restaurant_id' => '1234'], ], ], [ 'updateOne' => [ ['name' => 'Mongo\'s Deli'], ['$set' => ['cuisine' => 'Sandwiches and Salads']], ], ], [ 'deleteMany' => [ ['borough' => 'Manhattan'], ], ], ] );
注意
ライブラリが 一括操作を実行する場合、ターゲットコレクションの書込み保証 (write concern)が使用されます。ドライバーは、実行順序に関係なく、すべての操作を試行した後にすべての書込み保証 (write concern)エラーを報告します。
一括書き込み操作をカスタマイズする
オプション値を指定する配列をパラメーターとして渡すことで、 MongoDB\Collection::bulkWrite()
メソッドの動作を変更できます。 次の表では、 配列に設定できるオプションについて説明しています。
オプション | 説明 |
---|---|
| Specifies whether the operation bypasses document validation. This lets you
modify 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. The default is false . |
| Sets the codec to use for encoding or decoding documents. Bulk writes
use the codec for insertOne() and replaceOne() operations.
For more information, see the Codecs guide. |
| Sets the write concern for the operation.
For more information, see Write Concern
in the MongoDB Server manual. |
| Specifies a document with a list of values to improve operation readability.
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. |
| If set to true : When a single write fails, the operation stops without
performing the remaining writes and throws an exception.If set to false : When a single write fails, the operation continues to
attempt the remaining write operations, if any, then throws an exception.The default is true . |
| Attaches a comment to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
| Specifies the client session to associate with the operation. |
次の例では、 bulkWrite()
メソッドを呼び出して挿入操作と削除操作を実行し、 ordered
オプションをfalse
に設定します。
$result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ ['name' => 'Mongo\'s Pizza'], ['cuisine' => 'Italian'], ['borough' => 'Queens'], ['restaurant_id' => '5678'], ], ], [ 'deleteOne' => [ ['restaurant_id' => '5678'], ], ], ], ['ordered' => false] );
ライブラリが最初に挿入操作を実行した場合、ドキュメントが 1 つ削除されます。 削除操作が最初に実行される場合、ドキュメントは削除されません。
注意
順序なし動作
順序なしの一括操作では、実行順序は保証されません。 この順序は、ランタイムを最適化するために一覧表示する方法とは異なる場合があります。
戻り値
MongoDB\Collection::bulkWrite()
メソッドは MongoDB\BulkWriteResult
オブジェクトを返します。このクラスには、次のメソッドが含まれています。
方式 | 説明 |
---|---|
| Returns the total number of documents inserted by all
insert operations in the bulk write command. |
| Returns a map of _id field values for documents
inserted by all insert operations in the bulk write command. |
| Returns the total number of documents matched by all
update and replace operations in the bulk write command. |
| Returns the total number of documents modified by all update
and replace operations in the bulk write command. |
| Returns the total number of documents upserted by all update
and replace operations in the bulk write command. |
| Returns a map of _id field values for documents
upserted by all update and replace operations in the bulk write
command. |
| Return the total number of documents deleted by all delete
operations in the bulk write command. |
| Returns a boolean indicating whether the server acknowledged
the bulk operation. |
詳細情報
個々の書込み操作を実行する方法については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。
クライアント一括書込み (write)
コレクションの一括書込み (write)