一括操作
Overview
このガイドでは、 Node.jsドライバーを使用して 一括操作 を実行する方法を学習できます。一括操作は、サーバーへの呼び出しの回数を減らすのに役立ちます。各操作のリクエストを送信する代わりに、1 つのアクション内で複数の操作を実行できます。
Tip
一括操作の詳細については、 MongoDB Serverマニュアルの 一括書込み操作 を参照してください。
一括操作 を使用して、コレクションに対して複数の書込み (write) 操作を実行できます。クライアントから一括操作を実行することもできます。これにより、複数の名前空間にわたって一括書込みを実行できます。MongoDBでは、名前空間は<database>.<collection>
形式のデータベース名とコレクション名で構成されています。
このガイドには、次のセクションが含まれています。
一括挿入操作 では、コレクションまたはクライアントに対して 一括挿入操作 を実行する方法について説明します。
一括置換操作 では、コレクションまたはクライアントに対して一括置換操作を実行する方法について説明します。
一括更新操作 では、コレクションまたはクライアントに対して一括更新操作を実行する方法について説明します。
一括削除操作 では、コレクションまたはクライアントに対して一括削除操作を実行する方法について説明します。
例外の処理 では、一括書込み操作のいずれかの操作が失敗した場合に発生する例外について説明します。
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します。
重要
サーバーとドライバーのバージョンの要件
コレクション レベルの一括書き込み操作には、次のバージョンが必要です。
MongoDB Serverバージョン 3.2 以降
Node.jsドライバー バージョン 3.6 以降
クライアントレベルの一括書き込み操作には、次のバージョンが必要です。
MongoDB Serverバージョン 8.0 以降
Node.jsドライバー バージョン 6.10 以降
サンプル データ
このガイドの例では、Atlasサンプルデータセットに含まれる sample_mflix
データベース内の movies
コレクションと users
コレクションを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
一括挿入操作
一括挿入操作を実行するには、挿入するドキュメントごとに 一括操作モデル を作成します。次に、これらのモデルのリストを bulkWrite()
メソッドに渡します。
このセクションでは、次のタイプの一括操作を実行する方法について説明します。
コレクションの一括挿入
コレクションに対して 一括挿入操作 を実行するには、 各操作に対して InsertOneModel
を作成します。次に、コレクションで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。InsertOneModel
を作成するには、モデルの document
フィールドを指定し、挿入するドキュメントに設定します。
例
この例では、次のアクションを実行します。
配列内の 2 つの
InsertOneModel
インスタンスを指定します。各InsertOneModel
は、sample_mflix
データベース内のmovies
コレクションに挿入するドキュメントを表します。movies
コレクションでbulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。挿入されたドキュメントの数を出力します。
const insertModels = [{ insertOne: { document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } } }, { insertOne: { document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } } }]; const insertResult = await movies.bulkWrite(insertModels); console.log(`Inserted documents: ${insertResult.insertedCount}`);
Inserted documents: 2
クライアント一括挿入
複数のコレクションまたはデータベースにわたって一括挿入操作を実行するには、 各操作に対して ClientBulkWriteModel
を作成します。次に、クライアントで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。
次の表では、挿入操作を指定するために ClientBulkWriteModel
に設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The namespace in which to insert a document. Type: String |
| The operation you want to perform. For insert operations,
set this field to "insertOne" .Type: String |
| The document to insert. Type: Document |
例
この例では、次のアクションを実行します。
配列内の 3 つの
ClientBulkWriteModel
インスタンスを指定します。最初の 2 つのモデルはmovies
コレクションに挿入するドキュメントを表し、最後のモデルはusers
コレクションに挿入するドキュメントを表します。クライアントで
bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。挿入されたドキュメントの数を出力します。
const clientInserts = [{ namespace: "sample_mflix.movies", name: "insertOne", document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } }, { namespace: "sample_mflix.movies", name: "insertOne", document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } }, { namespace: "sample_mflix.users", name: "insertOne", document: { name: "Brian Schwartz", email: "bschwartz@example.com" } }]; const clientInsertRes = await client.bulkWrite(clientInserts); console.log(`Inserted documents: ${clientInsertRes.insertedCount}`);
Inserted documents: 3
一括置換操作
一括置換操作を実行するには、置き換えるドキュメントごとに 一括操作モデル を作成します。次に、これらのモデルのリストを bulkWrite()
メソッドに渡します。
このセクションでは、次のタイプの一括操作を実行する方法について説明します。
コレクションの一括置換
コレクションに対して 一括置換操作を実行するには、 各操作に対して ReplaceOneModel
を作成します。次に、コレクションで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。
次の表では、ReplaceOneModel
で設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collation section of the Configure CRUD Operations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: Bson |
| (Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false .Type: Boolean |
例
この例では、次のアクションを実行します。
配列内の 2 つの
ReplaceOneModel
インスタンスを指定します。ReplaceOneModel
インスタンスには、movies
コレクション内の映画を表すドキュメントを置き換えるための指示が含まれています。movies
コレクションでbulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。変更されたドキュメントの数を出力します。
const replaceOperations = [{ replaceOne: { filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" }, upsert: false } }, { replaceOne: { filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" }, upsert: false } }]; const replaceResult = await movies.bulkWrite(replaceOperations); console.log(`Modified documents: ${replaceResult.modifiedCount}`);
Modified documents: 2
クライアントの一括置換
複数のコレクションまたはデータベースにわたって一括置換操作を実行するには、 各操作に対して ClientBulkWriteModel
を作成します。次に、クライアントで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。
次の表では、置換操作を指定するために ClientBulkWriteModel
に設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The namespace in which to replace a document. Type: String |
| The operation you want to perform. For replace operations,
set this field to "replaceOne" .Type: String |
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collation section of the Configure CRUD Operations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: Bson |
例
この例では、次のアクションを実行します。
配列内の 3 つの
ClientBulkWriteModel
インスタンスを指定します。最初の 2 つのモデルにはmovies
コレクション内のドキュメントの置換手順が含まれ、最後のモデルにはusers
コレクション内のドキュメントの置換手順が含まれています。クライアントで
bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。変更されたドキュメントの数を出力します。
const clientReplacements = [{ namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" } }, { namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" } }, { namespace: "sample_mflix.users", name: "replaceOne", filter: { name: "April Cole" }, replacement: { name: "April Franklin", email: "aprilfrank@example.com" } }]; const clientReplaceRes = await client.bulkWrite(clientReplacements); console.log(`Modified documents: ${clientReplaceRes.modifiedCount}`);
Modified documents: 3
一括更新操作
一括更新操作を実行するには、実行する更新ごとに 一括操作モデル を作成します。次に、これらのモデルのリストを bulkWrite()
メソッドに渡します。
このセクションでは、次のタイプの一括操作を実行する方法について説明します。
コレクションの一括更新
コレクションに対して 一括更新操作 を実行するには、 各操作に対して UpdateOneModel
または UpdateManyModel
を作成します。次に、コレクションで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。UpdateOneModel
はフィルターに一致するドキュメントを1 つだけ更新し、UpdateManyModel
はフィルターに一致するすべてのドキュメントを更新します。
次の表では、UpdateOneModel
または UpdateManyModel
で設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The filter that matches one or more documents you want to update. When
specified in an UpdateOneModel , only the first matching document will
be updated. When specified in an UpdateManyModel , all matching documents
will be updated.Type: Document |
| The update to perform. Type: Document |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Array |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collation section of the Configure CRUD Operations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: String or Object |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
例
この例では、次のアクションを実行します。
配列で
UpdateOneModel
インスタンスとUpdateManyModel
インスタンスを指定します。 これらのモデルには、movies
コレクション内の映画を表すドキュメントを更新するための指示が含まれています。movies
コレクションでbulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。変更されたドキュメントの数を出力します。
const updateOperations = [{ updateOne: { filter: { title: "Interstellar" }, update: { $set: { title: "Interstellar Updated", genre: "Sci-Fi Adventure" } }, upsert: true } }, { updateMany: { filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } } } }]; const updateResult = await movies.bulkWrite(updateOperations); console.log(`Modified documents: ${updateResult.modifiedCount}`);
Modified documents: 2320
クライアントの一括更新
複数のコレクションまたはデータベースにわたって一括更新操作を実行するには、 各操作に対して ClientBulkWriteModel
を作成します。次に、クライアントで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。
次の表では、 更新操作を指定するために ClientBulkWriteModel
に設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The namespace in which to update a document. Type: String |
| The operation you want to perform. For update operations,
set this field to "updateOne" or "updateMany" .Type: String |
| The filter that matches one or more documents you want to update. If
you set the model name to "updateOne" , only the first matching
document is updated. If you set name to "updateMany" , all
matching documents are updated.Type: Document |
| The updates to perform. Type: Document or Document[] |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Document[] |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collation section of the Configure CRUD Operations guide. Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: Document or String |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
例
この例では、次のアクションを実行します。
配列内の 2 つの
ClientBulkWriteModel
インスタンスを指定します。最初のモデルはmovies
コレクションの更新操作数を指定し、2 番目のモデルはusers
コレクションの更新 1 つの操作を指定します。クライアントで
bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。変更されたドキュメントの数を出力します。
const clientUpdates = [{ namespace: "sample_mflix.movies", name: "updateMany", filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } }, upsert: false }, { namespace: "sample_mflix.users", name: "updateOne", filter: { name: "Jon Snow" }, update: { $set: { name: "Aegon Targaryen", email: "targaryen@example.com" } }, upsert: false }]; const clientUpdateRes = await client.bulkWrite(clientUpdates); console.log(`Modified documents: ${clientUpdateRes.modifiedCount}`);
Modified documents: 2320
一括削除操作
一括削除操作を実行するには、削除操作ごとに 一括操作モデル を作成します。次に、これらのモデルのリストを bulkWrite()
メソッドに渡します。
このセクションでは、次のタイプの一括操作を実行する方法について説明します。
コレクションの一括削除
コレクションに対して一括削除操作を実行するには、 各操作に対して DeleteOneModel
または DeleteManyModel
を作成します。次に、コレクションで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。DeleteOneModel
はフィルターに一致するドキュメントを1 つだけ削除し、DeleteManyModel
はフィルターに一致するすべてのドキュメントを削除します。
次の表では、DeleteOneModel
または DeleteManyModel
で設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The filter that matches one or more documents you want to delete. When
specified in a DeleteOneModel , only the first matching document will
be deleted. When specified in a DeleteManyModel , all matching documents
will be deleted.Type: Document |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collation section of the Configure CRUD Operations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: String or Object |
例
この例では、次のアクションを実行します。
配列で
DeleteOneModel
インスタンスとDeleteManyModel
インスタンスを指定します。これらのモデルには、movies
コレクション内のドキュメントを削除するための手順が含まれています。movies
コレクションでbulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。削除されたドキュメントの数を出力します。
const deleteOperations = [{ deleteOne: { filter: { title: "Dunkirk" } } }, { deleteMany: { filter: { rated: "R" } } }]; const deleteResult = await movies.bulkWrite(deleteOperations); console.log(`Deleted documents: ${deleteResult.deletedCount}`);
Deleted documents: 5538
クライアントの一括削除
複数のコレクションまたはデータベースにわたって一括削除操作を実行するには、 各操作に対して ClientBulkWriteModel
を作成します。次に、クライアントで bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。
次の表では、削除操作を指定するために ClientBulkWriteModel
に設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| The namespace in which to delete a document. Type: String |
| The operation you want to perform. For delete operations,
set this field to "deleteOne" or "deleteMany" .Type: String |
| The filter that matches one or more documents you want to delete. If
you set the model name to "deleteOne" , only the first matching
document is deleted. If you set name to "deleteMany" , all
matching documents are deleted.Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes on Collections guide. Type: Document or String |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collation section of the Configure CRUD Operations guide. Type: Document |
例
この例では、次のアクションを実行します。
配列内の 2 つの
ClientBulkWriteModel
インスタンスを指定します。最初のモデルはmovies
コレクションに対して多数の削除操作を指定し、2 番目のモデルはusers
コレクションに対して 1 つの削除操作を指定します。クライアントで
bulkWrite()
メソッドを呼び出し、モデルの配列をパラメーターとして渡します。変更されたドキュメントの数を出力します。
const clientDeletes = [{ namespace: "sample_mflix.movies", name: "deleteMany", filter: { rated: "R" } }, { namespace: "sample_mflix.users", name: "deleteOne", filter: { email: "emilia_clarke@gameofthron.es" } }]; const clientDeleteRes = await client.bulkWrite(clientDeletes); console.log(`Deleted documents: ${clientDeleteRes.deletedCount}`);
Deleted documents: 5538
戻り値の型
BulkWriteResult
Collection.bulkWrite()
メソッドは BulkWriteResult
オブジェクトを返します。これは 一括操作に関する情報を提供します。
次の表は、BulkWriteResult
オブジェクトのフィールドを説明します。
フィールド | 説明 |
---|---|
| 挿入されたドキュメントの数 |
| 一致したドキュメントの数 |
| 更新されたドキュメントの数 |
| アップサートされた文書の数 |
| 削除されたドキュメントの数 |
ClientBulkWriteResult
MongoClient.bulkWrite()
メソッドは、クライアントの一括書込み操作に関する情報を含む ClientBulkWriteResult
オブジェクトを返します。
次の表は、ClientBulkWriteResult
オブジェクトのフィールドを説明します。
フィールド | 説明 |
---|---|
| 一括書き込みが確認されたかどうかを示すブール値値 |
| 挿入されたドキュメントの数 |
| 一致したドキュメントの数 |
| 更新されたドキュメントの数 |
| アップサートされた文書の数 |
| 削除されたドキュメントの数 |
| 成功した各挿入操作の結果 |
| 成功した各更新操作の結果 |
| 成功した各削除操作の結果 |
例外の処理
コレクションの一括書込みの例外
コレクションで呼び出された一括書き込み操作が失敗した場合、ordered
オプションが true
に設定されている場合、 Node.jsドライバーは MongoBulkWriteError
をスローし、それ以上の操作を実行しません。ordered
が false
に設定されている場合、後続の操作への続行が試行されます。
MongoBulkWriteError
オブジェクトには次のプロパティが含まれています。
プロパティ | 説明 |
---|---|
| The error message. Type: String |
| An array of errors that occurred during the bulk write operation. Type: BulkWriteError[] |
| Write concern errors that occurred during execution of the bulk write operation. Type: WriteConnectionError[] |
| The results of any successful operations performed before the exception was
thrown. Type: BulkWriteResult[] |
| The underlying error object, which may contain more details. Type: Error |
クライアント一括書込みの例外
クライアントで呼び出される一括書き込み操作が失敗した場合、 Node.jsドライバーは MongoClientBulkWriteError
を生成します。デフォルトでは 、ドライバーはエラーが発生すると後続の操作を実行しません。ordered
オプションを bulkWrite()
メソッドに渡し、それを false
に設定すると、ドライバーは残りの操作を引き続き試行します。
MongoClientBulkWriteError
オブジェクトには次のプロパティが含まれています。
プロパティ | 説明 |
---|---|
| An array of documents specifying each write concern error. Type: Document[] |
| An map of errors that occurred during individual write operations. Type: Map<number, ClientBulkWriteError> |
| The partial result of the client bulk write that reflects the operation's
progress before the error. Type: ClientBulkWriteResult |
bulkWrite() の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。 MongoDBインスタンスへの接続の詳細については、「 MongoDBへの接続 」ガイドを参照してください。この例では、 Atlasサンプルデータセット に含まれる sample_mflix
データベースの movies
コレクションも使用します。 「 Atlas を使い始める 」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
次のコードは、sample_mflix
データベース内の theaters
コレクションに対して一括書き込み操作を実行する完全なスタンドアロンファイルです。 operations
パラメータには、insertOne
、updateMany
、deleteOne
の書き込み操作の例が含まれています。
1 // Bulk write operation 2 3 // Import MongoClient from the MongoDB node driver package 4 const { MongoClient } = require("mongodb"); 5 6 // Replace the uri string with your MongoDB deployment's connection string 7 const uri = "<connection string uri>"; 8 9 const client = new MongoClient(uri); 10 11 async function run() { 12 try { 13 const database = client.db("sample_mflix"); 14 const theaters = database.collection("theaters"); 15 16 // Insert a new document into the "theaters" collection 17 const result = await theaters.bulkWrite([ 18 { 19 insertOne: { 20 document: { 21 location: { 22 address: { 23 street1: "3 Main St.", 24 city: "Anchorage", 25 state: "AK", 26 zipcode: "99501", 27 }, 28 }, 29 }, 30 }, 31 }, 32 { 33 insertOne: { 34 document: { 35 location: { 36 address: { 37 street1: "75 Penn Plaza", 38 city: "New York", 39 state: "NY", 40 zipcode: "10001", 41 }, 42 }, 43 }, 44 }, 45 }, 46 { 47 // Update documents that match the specified filter 48 updateMany: { 49 filter: { "location.address.zipcode": "44011" }, 50 update: { $set: { is_in_ohio: true } }, 51 upsert: true, 52 }, 53 }, 54 { 55 // Delete a document that matches the specified filter 56 deleteOne: { filter: { "location.address.street1": "221b Baker St" } }, 57 }, 58 ]); 59 // Log the result of the bulk write operation 60 console.log(result); 61 } finally { 62 // Close the database connection when the operations are completed or if an error occurs 63 await client.close(); 64 } 65 } 66 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Address { 9 street1: string; 10 city: string; 11 state: string; 12 zipcode: string; 13 } 14 15 interface Theater { 16 location: { address: Address }; 17 is_in_ohio?: boolean; 18 } 19 20 async function run() { 21 try { 22 const database = client.db("sample_mflix"); 23 const theaters = database.collection<Theater>("theaters"); 24 25 const result = await theaters.bulkWrite([ 26 { 27 insertOne: { 28 document: { 29 location: { 30 address: { 31 street1: "3 Main St.", 32 city: "Anchorage", 33 state: "AK", 34 zipcode: "99501", 35 }, 36 }, 37 }, 38 }, 39 }, 40 { 41 insertOne: { 42 document: { 43 location: { 44 address: { 45 street1: "75 Penn Plaza", 46 city: "New York", 47 state: "NY", 48 zipcode: "10001", 49 }, 50 }, 51 }, 52 }, 53 }, 54 { 55 updateMany: { 56 // Important: You lose type safety when you use dot notation in queries 57 filter: { "location.address.zipcode": "44011" }, 58 update: { $set: { is_in_ohio: true } }, 59 upsert: true, 60 }, 61 }, 62 { 63 deleteOne: { 64 filter: { "location.address.street1": "221b Baker St" }, 65 }, 66 }, 67 ]); 68 69 console.log(result); 70 } finally { 71 await client.close(); 72 } 73 } 74 run().catch(console.dir);
上記の例を実行すると、次の出力が生成されます。
BulkWriteResult { insertedCount: 2, matchedCount: 1, modifiedCount: 1, deletedCount: 0, upsertedCount: 0, upsertedIds: {}, insertedIds: { '0': new ObjectId("..."), '1': new ObjectId("...") } }
詳細情報
一括操作の詳細については、 MongoDB Serverマニュアルの「 一括書込み 」を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。