Definition
New in version 8.0.
Starting in MongoDB 8.0, you can use the new bulkWrite
command to perform many insert, update, and delete operations on
multiple collections in one request. The existing
db.collection.bulkWrite() method only allows you to modify one
collection in one request.
To specify each collection in the bulkWrite command, use a
namespace (database and collection name).
Compatibility
This command is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The command has this syntax:
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> } )
In the command syntax, you can specify multiple:
Insert, update, and delete operations in any order in the
opsarray.Namespaces for the operations in the
nsInfoarray. To match the operation to the namespace, use the same namespace ID index. Indexes start at0. You can use sharded collections.
Command Fields
The command takes the following fields:
Field | Type | Necessity | Description |
|---|---|---|---|
| integer | Required | Namespace ID index for an insert operation, which must match a
namespace ID index in the |
| document | Required | Document to insert into the collection. |
| integer | Required | Namespace ID index for an update operation, which must match a
namespace ID index in the |
| document | Optional | Query selector to limit the documents for the update or delete operation. |
| document | Optional | Update operation to perform on the collection. You can specify one of these:
|
| document array | Optional | Array of filter documents that specify the documents to modify for an update operation on an array field. For details, see Array Update Operations with |
| boolean | Optional | If the Default is |
| document | Optional | Index to use for the document |
| document | Optional | Constants for an aggregation pipeline custom update. |
| document | Optional | Collation for an update or delete operation. |
| integer | Required | Namespace ID index for a delete operation, which must match a
namespace ID index in the |
| string | Required | Namespace (database and collection) for the operations. Set the
namespace ID index for each operation in |
| string | Optional | UUID hexadecimal value that specifies the collection for the operations. |
| document | Optional | Encryption information schema and tokens for the operation. For details, see Encryption Schemas. |
| boolean | Optional | If Ordered operations run in series. If an error occurs, any remaining operations are cancelled. Unordered operations run in parallel. If an error occurs, any remaining statements are run. The operations may be reordered by the server to increase performance. Therefore, your applications should not depend on the order of operation execution. Default is |
| boolean | Optional | If Default is |
| string | Optional | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:
A comment can be any valid BSON type (string, integer, object, array, etc). |
| document | Optional | Document with a list of constants to reference in the operation.
For |
| boolean | Optional | If Default is |
| integer | Optional | Cursor batch size for the |
| string | Optional | Write concern for the operation. Omit to use the server default. |
Output
The command returns a document with these fields:
Field | Type | Description |
|---|---|---|
| document | Cursor with the command results. |
| integer | Cursor identifier. |
| document array | Results of the operations. |
| integer |
|
| integer | Operation index number, which corresponds to the operation in the
|
| integer | Code number for an error. |
| string | Description for an error. |
| document | Document index key specification for an error. |
| document | Document index key value for an error. |
| integer | Total number of documents affected by an operation. |
| integer | Number of documents modified by an update operation. |
| integer | Number of errors for the |
| integer | Number of inserted documents. |
| integer | Number of matched documents. |
| integer | Number of modified documents. |
| integer | Number of upserted documents. |
| integer | Number of deleted documents. |
| integer |
|
Note
The output fields may vary depending on the operations you run in the
bulkWrite command.
Behavior
This section describes the bulkWrite command behavior.
Multiple Document Field and Retryable Writes
If the multi field is true, the update or delete operation
updates or deletes all documents that match the document filter. If
false, the operation updates or deletes the first document that
matches the document filter. For details on multi-document
transactions, see Transactions.
To enable retryable writes, see retryable writes.
You can use bulkWrite insert operations with retryable writes and
the multi field set to true.
You can use bulkWrite update and delete operations with the
multi field set to true. But, you cannot use update or delete
operations with both multi set to true and retryable writes.
Write Concern Errors in Sharded Clusters
Changed in version 8.1.2.
When bulkWrite executes on mongos in a sharded cluster, a writeConcernError is
always reported in the response, even when one or more other errors occur.
In previous releases, other errors sometimes caused bulkWrite to not report write concern errors.
For example, if a document fails validation, triggering a DocumentValidationFailed error,
and a write concern error also occurs, both the DocumentValidationFailed error and the
writeConcernError are returned in the top-level field of the response.
Operation Performance
If you rewrite existing insert, update, and delete commands as a
bulkWrite command and set errorsOnly to true, the
bulkWrite command has similar performance as the existing commands.
If you set errorsOnly to false, performance is worse.
In addition, if you have a sequence of commands like this:
insert update delete
If you replace those commands with the following example fragment, then the command with the following fragment is faster regardless of other options:
{ bulkWrite: 1, ops: [ insert, update, delete ] }
Most of the performance improvement is because of network latency, which is variable depending on your implementation, but the example is always faster.
Examples
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Single Namespace Bulk Write Example
The following bulkWrite example modifies a single namespace:
Modify the users collection
Run the following bulkWrite command to perform insert, update,
and delete operations on the users collection:
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 "sample_mflix.users" namespace in nsInfo at the end // of the example. // Insert a user. { insert: 0, document: { _id: ObjectId("67a1b2c3d4e5f6a7b8c9d0e1"), name: "Tyrion Lannister", email: "tyrion.lannister@example.com", password: "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu" } }, // Update the email for a user named Ned Stark. { update: 0, filter: { name: "Ned Stark" }, updateMods: { $set: { email: "ned.stark.updated@example.com" } } }, // Delete a user with a specific _id. { delete: 0, filter: { _id: ObjectId("67a1b2c3d4e5f6a7b8c9d0e1") } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "sample_mflix.users" } // Namespace ID index is 0. ] } )
The users collection is in the sample_mflix database, so
the ns namespace is "sample_mflix.users". The namespace ID index
is 0, which is set in the first field of the insert, update,
and delete operations in the ops array.
Examine the output
The following bulkWrite example output, with various ok: 1
fields and nErrors: 0, indicates all operations were
successful:
{ 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 }
For details about the output fields, see the earlier Output section.
Multiple Namespaces Bulk Write Example
You can specify multiple namespaces in a bulkWrite command.
The following bulkWrite example contains insert, update, and delete
operations for two namespaces:
Modify the collections
Run the following bulkWrite command to perform insert, update,
and delete operations on the users and sample_mflix.theaters collections:
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 "sample_mflix.users" // namespace. And, "insert: 1" specifies "sample_mflix.theaters". // Insert users. // Namespace ID is 0 for "sample_mflix.users", which // is specified as "insert: 0". { insert: 0, document: { _id: ObjectId("67a1b2c3d4e5f6a7b8c9d0e7"), name: "Sansa Stark", email: "sansa.stark@example.com", password: "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu" } }, { insert: 0, document: { _id: ObjectId("67a1b2c3d4e5f6a7b8c9d0e8"), name: "Bran Stark", email: "bran.stark@example.com", password: "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu" } }, // Update the email for a user. { update: 0, filter: { name: "Ned Stark" }, updateMods: { $set: { email: "lord.stark@example.com" } } }, // Delete users with a specific email pattern. { delete: 0, filter: { email: { $regex: "bran.stark" } } }, // Update theaters. // Namespace ID is 1 for "sample_mflix.theaters". { update: 1, filter: { theaterId: 1000 }, updateMods: { $set: { "location.address.city": "Minneapolis" } } }, // Delete a theater with a specific _id. { delete: 1, filter: { _id: ObjectId("59a47286cfa9a3a73e51e72c") } }, // Delete theaters in a specific state. { delete: 1, filter: { "location.address.state": "VT" }, multi: true } ], // Namespaces nsInfo: [ { ns: "sample_mflix.users" }, // Namespace ID index is 0. { ns: "sample_mflix.theaters" } // Namespace ID index is 1. ] } )
Examine the output
The following bulkWrite example output indicates the
operations were successful:
{ 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, nModified: 1 }, { ok: 1, idx: 5, n: 1 }, { ok: 1, idx: 6, n: 2 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 0, nInserted: 2, nMatched: 2, nModified: 2, nUpserted: 0, nDeleted: 4, ok: 1 }