Docs Menu
Docs Home
/ / /
Node.js ドライバー
/

一括操作

このガイドでは、 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フィールドを指定し、挿入するドキュメントに設定します。

この例では、次のアクションを実行します。

  1. 配列内の 2 つの InsertOneModel インスタンスを指定します。各 InsertOneModel は、sample_mflixデータベース内の moviesコレクションに挿入するドキュメントを表します。

  2. moviesコレクションで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 挿入されたドキュメントの数を出力します。

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 に設定できるフィールドについて説明しています。

フィールド
説明

namespace

The namespace in which to insert a document.
Type: String

name

The operation you want to perform. For insert operations, set this field to "insertOne".
Type: String

document

The document to insert.
Type: Document

この例では、次のアクションを実行します。

  1. 配列内の 3 つの ClientBulkWriteModel インスタンスを指定します。最初の 2 つのモデルは moviesコレクションに挿入するドキュメントを表し、最後のモデルは usersコレクションに挿入するドキュメントを表します。

  2. クライアントで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 挿入されたドキュメントの数を出力します。

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 で設定できるフィールドについて説明しています。

フィールド
説明

filter

The filter that matches the document you want to replace.
Type: Document

replacement

The replacement document.
Type: Document

collation

(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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: Bson

upsert

(Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false.
Type: Boolean

この例では、次のアクションを実行します。

  1. 配列内の 2 つの ReplaceOneModel インスタンスを指定します。 ReplaceOneModel インスタンスには、moviesコレクション内の映画を表すドキュメントを置き換えるための指示が含まれています。

  2. moviesコレクションで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 変更されたドキュメントの数を出力します。

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 に設定できるフィールドについて説明しています。

フィールド
説明

namespace

The namespace in which to replace a document.
Type: String

name

The operation you want to perform. For replace operations, set this field to "replaceOne".
Type: String

filter

The filter that matches the document you want to replace.
Type: Document

replacement

The replacement document.
Type: Document

collation

(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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: Bson

この例では、次のアクションを実行します。

  1. 配列内の 3 つの ClientBulkWriteModel インスタンスを指定します。最初の 2 つのモデルには moviesコレクション内のドキュメントの置換手順が含まれ、最後のモデルには usersコレクション内のドキュメントの置換手順が含まれています。

  2. クライアントで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 変更されたドキュメントの数を出力します。

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 で設定できるフィールドについて説明しています。

フィールド
説明

filter

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

update

The update to perform.
Type: Document

arrayFilters

(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.
Type: Array

collation

(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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: String or Object

upsert

(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false.
Type: Boolean

この例では、次のアクションを実行します。

  1. 配列で UpdateOneModel インスタンスと UpdateManyModelインスタンスを指定します。 これらのモデルには、 moviesコレクション内の映画を表すドキュメントを更新するための指示が含まれています。

  2. moviesコレクションで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 変更されたドキュメントの数を出力します。

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 に設定できるフィールドについて説明しています。

フィールド
説明

namespace

The namespace in which to update a document.
Type: String

name

The operation you want to perform. For update operations, set this field to "updateOne" or "updateMany".
Type: String

filter

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

update

The updates to perform.
Type: Document or Document[]

arrayFilters

(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.
Type: Document[]

collation

(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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: Document or String

upsert

(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false.
Type: Boolean

この例では、次のアクションを実行します。

  1. 配列内の 2 つの ClientBulkWriteModel インスタンスを指定します。最初のモデルは moviesコレクションの更新操作数を指定し、2 番目のモデルは usersコレクションの更新 1 つの操作を指定します。

  2. クライアントで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 変更されたドキュメントの数を出力します。

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 で設定できるフィールドについて説明しています。

フィールド
説明

filter

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

collation

(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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: String or Object

この例では、次のアクションを実行します。

  1. 配列で DeleteOneModel インスタンスと DeleteManyModelインスタンスを指定します。これらのモデルには、moviesコレクション内のドキュメントを削除するための手順が含まれています。

  2. moviesコレクションで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 削除されたドキュメントの数を出力します。

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 に設定できるフィールドについて説明しています。

フィールド
説明

namespace

The namespace in which to delete a document.
Type: String

name

The operation you want to perform. For delete operations, set this field to "deleteOne" or "deleteMany".
Type: String

filter

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

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes on Collections guide.
Type: Document or String

collation

(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

この例では、次のアクションを実行します。

  1. 配列内の 2 つの ClientBulkWriteModel インスタンスを指定します。最初のモデルは moviesコレクションに対して多数の削除操作を指定し、2 番目のモデルは usersコレクションに対して 1 つの削除操作を指定します。

  2. クライアントで bulkWrite() メソッドを呼び出し、モデルの配列をパラメーターとして渡します。

  3. 変更されたドキュメントの数を出力します。

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

Collection.bulkWrite() メソッドは BulkWriteResultオブジェクトを返します。これは 一括操作に関する情報を提供します。

次の表は、BulkWriteResultオブジェクトのフィールドを説明します。

フィールド
説明

insertedCount

挿入されたドキュメントの数

matchedCount

一致したドキュメントの数

modifiedCount

更新されたドキュメントの数

upsertedCount

アップサートされた文書の数

deletedCount

削除されたドキュメントの数

MongoClient.bulkWrite() メソッドは、クライアントの一括書込み操作に関する情報を含む ClientBulkWriteResultオブジェクトを返します。

次の表は、ClientBulkWriteResultオブジェクトのフィールドを説明します。

フィールド
説明

acknowledged

一括書き込みが確認されたかどうかを示すブール値値

insertedCount

挿入されたドキュメントの数

matchedCount

一致したドキュメントの数

modifiedCount

更新されたドキュメントの数

upsertedCount

アップサートされた文書の数

deletedCount

削除されたドキュメントの数

insertResults

成功した各挿入操作の結果

updateResults

成功した各更新操作の結果

deleteResults

成功した各削除操作の結果

コレクションで呼び出された一括書き込み操作が失敗した場合、ordered オプションが true に設定されている場合、 Node.jsドライバーは MongoBulkWriteError をスローし、それ以上の操作を実行しません。orderedfalse に設定されている場合、後続の操作への続行が試行されます。

Tip

順序付き一括操作と順序なし一括操作の詳細については、 MongoDB Serverマニュアルの 一括書込みガイドの「 順序付き操作と順序なし操作 」セクションを参照してください。

MongoBulkWriteErrorオブジェクトには次のプロパティが含まれています。

プロパティ
説明

message

The error message.
Type: String

writeErrors

An array of errors that occurred during the bulk write operation.
Type: BulkWriteError[]

writeConcernErrors

Write concern errors that occurred during execution of the bulk write operation.
Type: WriteConnectionError[]

result

The results of any successful operations performed before the exception was thrown.
Type: BulkWriteResult[]

err

The underlying error object, which may contain more details.
Type: Error

クライアントで呼び出される一括書き込み操作が失敗した場合、 Node.jsドライバーは MongoClientBulkWriteError を生成します。デフォルトでは 、ドライバーはエラーが発生すると後続の操作を実行しません。ordered オプションを bulkWrite() メソッドに渡し、それを false に設定すると、ドライバーは残りの操作を引き続き試行します。

MongoClientBulkWriteErrorオブジェクトには次のプロパティが含まれています。

プロパティ
説明

writeConcernErrors

An array of documents specifying each write concern error.
Type: Document[]

writeErrors

An map of errors that occurred during individual write operations.
Type: Map<number, ClientBulkWriteError>

partialResult

The partial result of the client bulk write that reflects the operation's progress before the error.
Type: ClientBulkWriteResult

注意

セットアップ例

この例では、接続 URI を使用してMongoDBのインスタンスに接続します。 MongoDBインスタンスへの接続の詳細については、「 MongoDBへの接続 」ガイドを参照してください。この例では、 Atlasサンプルデータセット に含まれる sample_mflixデータベースの moviesコレクションも使用します。 「 Atlas を使い始める 」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

次のコードは、sample_mflixデータベース内の theatersコレクションに対して一括書き込み操作を実行する完全なスタンドアロンファイルです。 operations パラメータには、insertOneupdateManydeleteOne の書き込み操作の例が含まれています。

1// Bulk write operation
2
3// Import MongoClient from the MongoDB node driver package
4const { MongoClient } = require("mongodb");
5
6// Replace the uri string with your MongoDB deployment's connection string
7const uri = "<connection string uri>";
8
9const client = new MongoClient(uri);
10
11async 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}
66run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Address {
9 street1: string;
10 city: string;
11 state: string;
12 zipcode: string;
13}
14
15interface Theater {
16 location: { address: Address };
17 is_in_ohio?: boolean;
18}
19
20async 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}
74run().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 ドキュメントを参照してください。

戻る

Delete Documents