定義
バージョン8.0の新機能。
MongoDB 8.0以降では、新しい bulkWriteコマンドを使用して、複数のコレクションに対して多くの挿入、アップデート、削除操作を 1 回のリクエストで実行できます。 既存の db.collection.bulkWrite()メソッドでは、1 回のリクエストで 1 つのコレクションのみを変更できます。
bulkWriteコマンドで各コレクションを指定するには、名前空間(データベースとコレクション名)を使用します。
互換性
このコマンドは、次の環境でホストされている配置で使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
注意
このコマンドは、すべての MongoDB Atlas クラスターでサポートされています。すべてのコマンドに対する Atlas のサポートについては、「サポートされていないコマンド」を参照してください。
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
コマンドの構文は次のとおりです。
db.adminCommand( { bulkWrite: 1, // Include the insert, update, and delete operations // in the ops array ops: [ { insert: <integer>, // Namespace ID index for insert operation. // Must match a namespace ID index in // ns specified later in the nsInfo array. document: <document> }, { update: <integer>, // Namespace ID index for update operation filter: <document>, updateMods: <document>, arrayFilters: [ <filterDocument0>, <filterDocument1>, ... ], multi: <bolean>, hint: <document>, constants: <document>, collation: <document> }, { delete: <integer>, // Namespace ID index for delete operation filter: <document>, multi: <boolean>, hint: <document>, collation: <document> }, ... // Additional insert, update, and delete operations in any order ... ], // Include the namespaces with collections to modify // in the nsInfo array. You can add multiple namespaces here. nsInfo: [ { ns: <string>, // Namespace (database and collection name) to modify. // Each operation namespace ID index // specified in the earlier ops array must // match a namespace ID index here. collectionUUID: <string>, encryptionInformation: <document> }, ... // Additional namespaces ... ], // Additional fields ordered: <boolean>, bypassDocumentValidation: <boolean>, comment: <string>, let: <document>, errorsOnly: <boolean>, cursor: { batchSize: <integer> }, writeConcern: <string> } )
コマンド構文では、複数の を指定できます。
ops配列内で任意の順序で挿入、アップデート、削除操作が実行できます。nsInfo配列内の操作の名前空間。 操作を名前空間と一致させるには、同じ名前空間IDインデックスを使用します。 インデックスは0から開始されます。 シャーディングされたコレクションを使用できます。
コマンドフィールド
このコマンドは、次のフィールドを使用します。
フィールド | タイプ | 必要性 | 説明 |
|---|---|---|---|
| integer | 必須 | 挿入操作の名前空間IDインデックス。この操作は、 |
| ドキュメント | 必須 | コレクションに挿入するドキュメント 。 |
| integer | 必須 | 更新操作の名前空間IDインデックス。この操作は、 |
| ドキュメント | 任意 | アップデートまたは削除操作のドキュメントを制限するクエリ セレクター。 |
| ドキュメント | 任意 | |
| ドキュメント配列 | 任意 | 配列フィールドの更新操作で変更するドキュメントを指定するフィルター ドキュメントの配列。 詳細については、「 |
| ブール値 | 任意 |
デフォルトは、 |
| ドキュメント | 任意 | ドキュメント |
| ドキュメント | 任意 | 集計パイプラインカスタム更新の制約。 |
| ドキュメント | 任意 | アップデートまたは削除操作の照合。 |
| integer | 必須 | 削除操作の名前空間IDインデックス。この操作は、 |
| string | 必須 | 操作の名前空間(データベースとコレクション)。 |
| string | 任意 | 操作のコレクションを指定するUUIDの 16進値。 |
| ドキュメント | 任意 | 操作の暗号化情報スキーマとトークン。 詳細については、「暗号化スキーマ 」を参照してください。 |
| ブール値 | 任意 |
順序付き操作は連続して実行されます。 エラーが発生した場合、残りの操作はすべてキャンセルされます。 順序付けられていない操作が並列に実行されます。 エラーが発生した場合、残りのステートメントが実行されます。 パフォーマンスを向上させるために、サーバーによって操作の順序が並べ替えられる場合があります。 したがって、アプリケーションは操作の実行順序に依存すべきではありません。 デフォルトは、 |
| ブール値 | 任意 |
デフォルトは、 |
| string | 任意 | 任意。このコマンドに添付するユーザー指定のコメント。設定すると、このコメントは以下の場所にこのコマンドの記録と合わせて表示されます。
コメントには、有効な BSON 型(string, integer, object, array など)を使用できます。 |
| ドキュメント | 任意 | 操作で参照する定数のリストを含むドキュメント。 |
| ブール値 | 任意 |
デフォルトは、 |
| integer | 任意 |
|
| string | 任意 | 操作の書込み保証 ( write concern ) 。 サーバーのデフォルトを使用する場合は省略します。 |
出力
このコマンドは、次のフィールドを含むドキュメントを返します。
フィールド | タイプ | 説明 |
|---|---|---|
| ドキュメント | コマンドの結果を持つカーソル。 |
| integer | カーソル識別子。 |
| ドキュメント配列 | 操作の結果。 |
| integer |
|
| integer |
|
| integer | エラーのコード番号。 |
| string | エラーの説明。 |
| ドキュメント | エラーのドキュメントインデックスキーの指定。 |
| ドキュメント | エラーのドキュメントインデックスキー値。 |
| integer | 操作の影響を受けるドキュメントの合計数。 |
| integer | 更新操作によって変更されたドキュメントの数。 |
| integer |
|
| integer | 挿入されたドキュメントの数。 |
| integer | 一致したドキュメントの数。 |
| integer | 変更されたドキュメントの数。 |
| integer | アップサートされたドキュメントの数。 |
| integer | 削除されたドキュメントの数。 |
| integer |
|
注意
出力フィールドは、 bulkWriteコマンドで実行する操作によって異なる場合があります。
動作
このセクションでは、 bulkWriteコマンドの動作について説明します。
複数のドキュメント フィールドと再試行可能な書込み
multiフィールドがtrueの場合、更新操作または削除操作により、ドキュメントfilterに一致するすべてのドキュメントが更新または削除されます。 falseの場合、操作によってドキュメントfilterと一致する 最初のドキュメントが更新または削除されます。 マルチドキュメントトランザクションの詳細については、「トランザクション 」を参照してください。
再試行可能な書込みを有効にするには、「再試行可能な書込み 」を参照してください。
再試行可能な書き込みと、 multiフィールドをtrueに設定すると、 bulkWrite挿入操作を使用できます。
multiフィールドをtrueに設定すると、 bulkWriteのアップデート操作と削除操作を使用できます。 ただし、 multiがtrueと再試行可能な書き込みの両方でアップデート操作または削除操作を使用することはできません。
シャーディングされたクラスターでの書込み保証 (write concern) エラー
バージョン8.1.2で変更。
bulkWrite がシャーディングされたクラスター内の mongos で実行されると、他のエラーが 1 つ以上発生した場合でも、レスポンスには常に writeConcernError が報告されます。以前のリリースでは、他のエラーによって bulkWrite が書込み保証 (write concern)エラーを報告しないことがあります。
例、ドキュメントが検証に失敗して DocumentValidationFailed エラーが発生し、書込み保証 (write concern)エラーも発生した場合、DocumentValidationFailed エラーと writeConcernError の両方が応答の最上位フィールドに返されます。
操作パフォーマンス
既存の挿入、更新、削除コマンドをbulkWriteコマンドとして書き換え、 errorsOnlyをtrueに設定すると、 bulkWriteコマンドは既存のコマンドと同様のパフォーマンスになります。 errorsOnlyをfalseに設定すると、パフォーマンスは低下します。
さらに、次のような一連のコマンドがある場合は次のようになります。
insert update delete
これらのコマンドを次の例のフラグメントで置き換えると、次のフラグメントを含むコマンドは、他のオプションに関係なく高速になります。
{ bulkWrite: 1, ops: [ insert, update, delete ] }
パフォーマンス向上のほとんどは、 ネットワークレイテンシが原因です。これは実装によって異なりますが、例は常に高速です。
例
このセクションには、 bulkWriteコマンドの例が含まれています。
単一名前空間一括書込みの例
次のbulkWriteの例では、1 つの名前空間を変更しています。
ピザの例コレクションを変更します
次のbulkWriteコマンドを実行して、 pizzasコレクションに対して挿入、アップデート、削除操作を実行します。
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // Specify the namespace ID index immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo at the end // of the example. // Insert a pizza. { insert: 0, document: { _id: 4, type: "sausage", size: "small", price: 12 } }, // Update the price for medium pizzas. { update: 0, filter: { size: "medium" }, updateMods: { $set: { price: 15 } } }, // Delete the pizza with an _id of 2. { delete: 0, filter: { _id: 2 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ] } )
pizzasコレクションはデフォルトのtestデータベースにあるため、 ns名前空間は"test.pizzas"です。 名前空間IDインデックスは0で、これはops配列の挿入、アップデート、削除操作の最初のフィールドに設定されています。
出力を確認します。
さまざまなok: 1フィールドとnErrors: 0を例次のbulkWriteの出力は、すべての操作が成功したことを示しています。
{ cursor: { id: Long('0'), firstBatch: [ { ok: 1, idx: 0, n: 1 }, { ok: 1, idx: 1, n: 1, nModified: 1 }, { ok: 1, idx: 2, n: 1 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 0, nInserted: 1, nMatched: 1, nModified: 1, nUpserted: 0, nDeleted: 1, ok: 1 }
出力フィールドの詳細については、以前の出力セクションを参照してください。
複数の名前空間の一括書込みの例
bulkWriteコマンドで複数の名前空間を指定できます。
次のbulkWriteの例には、2 つの名前空間に対する挿入、アップデート、削除操作が含まれています。
ピザの例コレクションを作成する
testデータベースにpizzasコレクションがすでにある場合は、 db.collection.drop()メソッドを使用してまず削除し、次に次のコマンドを実行します。
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
ピザ注文の例コレクションを作成する
実行:
db.pizzaOrders.insertMany( [ { _id: 0, type: "pepperoni", number: 5, orderDate: new Date( "2023-01-15T12:00:00Z" ) }, { _id: 1, type: "cheese", number: 15, orderDate: new Date( "2023-01-23T11:12:32Z" ) }, { _id: 2, type: "vegan", number: 20, orderDate: new Date( "2023-03-20T10:01:12Z" ) } ] )
例コレクションを変更します
次のbulkWriteコマンドを実行して、例コレクションに対して挿入、アップデート、削除操作を実行します。
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // Specify the namespace ID indexes immediately after // the insert, update, and delete. For example, "insert: 0" // specifies the 0 namespace ID index, which is the "test.pizzas" // namespace. And, "insert: 1" specifies "test.pizzaOrders". // Insert pizzas. // Namespace ID is 0 for "test.pizzas", which // is specified as "insert: 0". { insert: 0, document: { _id: 5, type: "sausage", size: "small", price: 12 } }, { insert: 0, document: { _id: 6, type: "vegan cheese", size: "large", price: 25 } }, // Update the price for cheese pizzas. { update: 0, filter: { type: "cheese" }, updateMods: { $set: { price: 15 } } }, // Delete pizzas with a price less than 7. { delete: 0, filter: { price: { $lt: 7 } } }, // Insert pizza orders. // Namespace ID is 1 for "test.pizzaOrders". { insert: 1, document: { _id: 3, type: "sausage", number: 7, orderDate: new Date( "2023-04-15T12:02:15Z" ) } }, { insert: 1, document: { _id: 4, type: "vegan", number: 16, orderDate: new Date( "2023-05-12T11:03:11Z" ) } }, // Update the number of pizza orders for cheese pizzas. { update: 1, filter: { type: "cheese" }, updateMods: { $set: { number: 50 } } }, // Delete the pizza order with an _id of 2. { delete: 1, filter: { _id: 2 } }, // Delete pizza orders placed before March 15, 2023. { delete: 1, filter: { orderDate: { $lte: ISODate( "2023-03-15T00:00:00Z" ) } } } ], // Namespaces nsInfo: [ { ns: "test.pizzas" }, // Namespace ID index is 0. { ns: "test.pizzaOrders" } // Namespace ID index is 1. ] } )
出力を確認します。
次のbulkWriteの出力の例は、操作が成功したことを示しています。
{ cursor: { id: Long('0'), firstBatch: [ { ok: 1, idx: 0, n: 1 }, { ok: 1, idx: 1, n: 1 }, { ok: 1, idx: 2, n: 1, nModified: 1 }, { ok: 1, idx: 3, n: 1 }, { ok: 1, idx: 4, n: 1 }, { ok: 1, idx: 5, n: 1 }, { ok: 1, idx: 6, n: 1, nModified: 1 }, { ok: 1, idx: 7, n: 1 }, { ok: 1, idx: 8, n: 1 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 0, nInserted: 4, nMatched: 2, nModified: 2, nUpserted: 0, nDeleted: 3, ok: 1 }
エラーを含む操作の一括書込みの例
次のbulkWriteの例には、エラーのある操作とドキュメントを変更しない操作が含まれています。
ピザの例コレクションを作成する
testデータベースにpizzasコレクションがすでにある場合は、 db.collection.drop()メソッドを使用してまず削除し、次に次のコマンドを実行します。
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
ピザの例コレクションの変更を試みる
次のbulkWriteコマンドを実行して、 pizzasコレクションに対して挿入、アップデート、削除操作を実行します。
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // The namespace ID indexes are specified immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo. // Attempt to add a duplicate document with an // _id of 1, which already exists and causes an error. { insert: 0, document: { _id: 1, type: "tomato", size: "small", price: 12 } }, // Attempt to add another duplicate document. { insert: 0, document: { _id: 2, type: "pepper", size: "small", price: 12 } }, // Attempt to change the price for extra large pizzas, // which don't exist. This doesn't cause an error but // doesn't update any documents. { update: 0, filter: { size: "extra large" }, updateMods: { $set: { price: 15 } } }, // Attempt to remove a document that doesn't exist. // This doesn't cause an error but doesn't delete any documents. { delete: 0, filter: { _id: 8 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ], // Set the ordered field to false to run the remaining operations // after an operation returns an error. ordered: false } )
出力を確認します。
次のbulkWrite出力の例は、 エラーを示しています。
{ cursor: { id: Long("0"), firstBatch: [ { ok: 0, idx: 0, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 1 }', keyPattern: { _id: 1 }, keyValue: { _id: 1 }, n: 0 }, { ok: 0, idx: 1, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 2 }', keyPattern: { _id: 1 }, keyValue: { _id: 2 }, n: 0 }, { ok: 1, idx: 2, n: 0, nModified: 0 }, { ok: 1, idx: 3, n: 0 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 2, nInserted: 0, nMatched: 0, nModified: 0, nUpserted: 0, nDeleted: 0, ok: 1 }
エラー コードやメッセージを含む出力フィールドの詳細については、以前の「出力」セクションを参照してください。
errorsOnly が有効な場合の一括書込みの例
次のbulkWriteの例では、 errorsOnlyをtrueに設定して、エラー出力のみを表示します。
ピザの例コレクションを作成する
testデータベースにpizzasコレクションがすでにある場合は、 db.collection.drop()メソッドを使用してまず削除し、次に次のコマンドを実行します。
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
ピザの例コレクションの変更を試みる
次のbulkWriteコマンドを実行し、 errorsOnlyをtrueに設定して、 pizzasコレクションに対して挿入、アップデート、削除操作を実行します。
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // The namespace ID indexes are specified immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo. // Attempt to add a duplicate document with an // _id of 1, which already exists and causes an error. { insert: 0, document: { _id: 1, type: "tomato", size: "small", price: 12 } }, // Attempt to add another duplicate document. { insert: 0, document: { _id: 2, type: "pepper", size: "small", price: 12 } }, // Attempt to change the price for extra large pizzas, // which don't exist. This doesn't cause an error but // doesn't update any documents. { update: 0, filter: { size: "extra large" }, updateMods: { $set: { price: 15 } } }, // Attempt to remove a document that doesn't exist. // This doesn't cause an error but doesn't delete any documents. { delete: 0, filter: { _id: 8 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ], // Set the ordered field to false to run the remaining operations // after an operation returns an error. ordered: false, // Set the errorsOnly field to true to only output the errors. errorsOnly: true } )
出力を確認します。
次のbulkWrite出力の例は、 エラーを示しています。
{ cursor: { id: Long("0"), firstBatch: [ { ok: 0, idx: 0, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 1 }', keyPattern: { _id: 1 }, keyValue: { _id: 1 }, n: 0 }, { ok: 0, idx: 1, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 2 }', keyPattern: { _id: 1 }, keyValue: { _id: 2 }, n: 0 }, ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 2, nInserted: 0, nMatched: 0, nModified: 0, nUpserted: 0, nDeleted: 0, ok: 1 }