Docs Menu

一括操作

このガイドでは、 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サンプルデータセット に含まれる データベース内のmovies usersコレクションとsample_mflix コレクションを使用します。 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.
タイプ: String

name

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

document

The document to insert.
タイプ: 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.
タイプ: Document

replacement

The replacement document.
タイプ: Document

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
Type: String or Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
タイプ: Bson

upsert

(Optional) Whether a new document is created if no document matches the filter.
デフォルトでは 、このフィールドは false に設定されています。
タイプ: 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.
タイプ: String

name

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

filter

The filter that matches the document you want to replace.
タイプ: Document

replacement

The replacement document.
タイプ: Document

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
Type: String or Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
タイプ: 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.
タイプ: Document

update

The update to perform.
タイプ: Document

arrayFilters

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

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
タイプ: Object

hint

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

upsert

(任意) フィルター に一致するドキュメントがない場合に新しいドキュメントを作成するかどうか。 デフォルトでは 、このフィールドは false に設定されています。
タイプ: 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.
タイプ: String

name

The operation you want to perform. For update operations, set this field to "updateOne" or "updateMany".
タイプ: 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.
タイプ: 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.
タイプ: Document[]

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
タイプ: Document

hint

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

upsert

(任意) フィルター に一致するドキュメントがない場合に新しいドキュメントを作成するかどうか。 デフォルトでは 、このフィールドは false に設定されています。
タイプ: 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.
タイプ: Document

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
タイプ: Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
タイプ: 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.
タイプ: String

name

The operation you want to perform. For delete operations, set this field to "deleteOne" or "deleteMany".
タイプ: 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.
タイプ: Document

hint

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

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
タイプ: 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.
タイプ: String

writeErrors

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

writeConcernErrors

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

result

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

err

The underlying error object, which may contain more details.
タイプ: Error

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

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

プロパティ
説明

writeConcernErrors

An array of documents specifying each write concern error.
タイプ: Document[]

writeErrors

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

partialResult

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

一括操作の詳細については、 MongoDB Serverマニュアルの「 一括書込み 」を参照してください。

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