> This page location: /docs.md > /docs/development.md > /docs/manual/reference/method.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: updateOne, updateMany, deleteOne, deleteMany
-->

# db.collection.bulkWrite() (mongosh method)

**Note: New Bulk Write Command in MongoDB 8.0**

Starting in MongoDB 8.0, you can use the [`Mongo.bulkWrite()`](https://www.mongodb.com/docs/manual/reference/method/mongo.bulkwrite.md#mongodb-method-Mongo.bulkWrite) `mongosh` method to perform bulk writes across multiple databases and collections. To learn more about different bulk write methods and commands, see [Bulk Write Operations.](https://www.mongodb.com/docs/manual/core/bulk-write-operations.md#std-label-bulk-write-operations)

## Definition

Performs multiple write operations on **one** collection, with controls for order of execution.

- A boolean `acknowledged` as `true` if the operation ran with [write concern](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-write-concern) or `false` if write concern was disabled.

- A count for each write operation.

- An array containing an `_id` for each successfully inserted or upserted documents.

## Compatibility

`db.collection.bulkWrite()` is available in deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/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.](https://www.mongodb.com/docs/atlas/unsupported-commands/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

**Note:**

You can't perform [bulk write](https://www.mongodb.com/docs/manual/core/bulk-write-operations.md#std-label-bulk-write-operations) operations in the [Atlas UI](https://www.mongodb.com/docs/atlas/atlas-ui/documents.md#std-label-atlas-ui-docs). To insert multiple documents, you must insert an array of documents. To learn more, see [Create, View, Update, and Delete Documents](https://www.mongodb.com/docs/atlas/atlas-ui/documents.md#std-label-atlas-ui-docs) in the Atlas documentation.

## Syntax

The [`bulkWrite()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#mongodb-method-db.collection.bulkWrite) method has the following form:

```javascript
db.collection.bulkWrite(
    [ <operation 1>, <operation 2>, ... ],
    {
      writeConcern : <document>,
      ordered : <boolean>
    }
)
```

### Parameters

The `bulkWrite()` method takes the following parameters:

| Parameter | Type | Description |
| --- | --- | --- |
| `operations` | array | An array of `bulkWrite()` write operations. Valid operations are: [insertOne](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-insertOne); [updateOne](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-updateOneMany); [updateMany](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-updateOneMany); [deleteOne](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-deleteOneMany); [deleteMany](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-deleteOneMany); [replaceOne](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-replaceOne) See [Write Operations](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations) for usage of each operation |
| `writeConcern` | document | Optional. A document expressing the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-write-concern). Omit to use the default write concern. Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see [Transactions and Write Concern.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-write-concern) |
| `ordered` | boolean | Optional. A boolean specifying whether operations execute serially (`true`, the default) or may execute in any order (`false`). When `true`, stops on the first error; when `false`, continues processing remaining operations. |

## Behavior

`bulkWrite()` takes an array of write operations and executes each of them. By default operations are executed in order. See [Execution of Operations](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-write-operations-executionofoperations) for controlling the order of write operation execution.

### Write Operations

#### insertOne

Inserts a single document into the collection.

```javascript
db.collection.bulkWrite( [
   { insertOne : { "document" : <document> } }
] )
```

#### updateOne and updateMany

### updateOne

`updateOne` updates a *single* document in the collection that matches the filter. If multiple documents match, `updateOne` will update the *first* matching document only.

```javascript
db.collection.bulkWrite( [
   { updateOne :
      {
         "filter": <document>,
         "update": <document or pipeline>,
         "upsert": <boolean>,
         "collation": <document>,
         "arrayFilters": [ <filterdocument1>, ... ],
         "hint": <document|string>
      }
   }
] )
```

| Field | Notes |
| --- | --- |
| `filter` | The selection criteria for the update. The same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as in the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method are available. |
| `update` | The update operation to perform. Can specify either: A document that only contains [update operator](https://www.mongodb.com/docs/manual/reference/mql/update.md#std-label-update-operators) expressions.; An [aggregation pipeline](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-aggregation-pipeline) `[ <stage1>, <stage2>, ... ]` that specifies the modifications to perform. |
| `upsert` | Optional. A boolean to indicate whether to perform an upsert. By default, `upsert` is `false`. |
| `arrayFilters` | Optional. An array of filter documents that determine which array elements to modify for an update operation on an array field. |
| `collation` | Optional. Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) to use for the operation. |
| `hint` | Optional. The [index](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) to use to support the update `filter`. If you specify an index that does not exist, the operation errors. |

#### replaceOne

`replaceOne` replaces a *single* document in the collection that matches the filter. If multiple documents match, `replaceOne` will replace the *first* matching document only.

```javascript
db.collection.bulkWrite([
   { replaceOne :
      {
         "filter" : <document>,
         "replacement" : <document>,
         "upsert" : <boolean>,
         "collation": <document>,
         "hint": <document|string>
      }
   }
] )
```

| Field | Notes |
| --- | --- |
| `filter` | The selection criteria for the replacement operation. The same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as in the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method are available. |
| `replacement` | The replacement document. The document cannot contain [update operators.](https://www.mongodb.com/docs/manual/reference/mql/update.md#std-label-update-operators) |
| `upsert` | Optional. A boolean to indicate whether to perform an upsert. By default, `upsert` is `false`. |
| `collation` | Optional. Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) to use for the operation. |
| `hint` | Optional. The [index](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) to use to support the update `filter`. If you specify an index that does not exist, the operation errors. |

#### deleteOne and deleteMany

### deleteOne

`deleteOne` deletes a *single* document in the collection that match the filter. If multiple documents match, `deleteOne` will delete the *first* matching document only.

```javascript
db.collection.bulkWrite([
   { deleteOne : {
      "filter" : <document>,
      "collation" : <document>                   // Available starting in 3.4
   } }
] )
```

| Field | Notes |
| --- | --- |
| `filter` | The selection criteria for the delete operation. The same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as in the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method are available. |
| `collation` | Optional. Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) to use for the operation. |

### `_id` Field

If the document does not specify an [\_id](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-_id) field, then [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) adds the `_id` field and assign a unique [`ObjectId()`](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-ObjectId) for the document before inserting or upserting it. Most drivers create an ObjectId and insert the `_id` field, but the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) will create and populate the `_id` if the driver or application does not.

If the document contains an `_id` field, the `_id` value must be unique within the collection to avoid duplicate key error.

Update or replace operations cannot specify an `_id` value that differs from the original document.

### Execution of Operations

The `ordered` parameter controls whether operations execute serially or in any order.

With `ordered : true` (default), operations execute serially. If an error occurs, subsequent operations are not executed.

With `ordered : false`, operations may execute in parallel. All operations without errors are completed even if some operations fail.

The number of operations in each group cannot exceed the value of the [maxWriteBatchSize](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Write-Command-Batch-Limit-Size) of the database. The default value of `maxWriteBatchSize` is `100,000`. This value is shown in the [`hello.maxWriteBatchSize`](https://www.mongodb.com/docs/manual/reference/command/hello.md#mongodb-data-hello.maxWriteBatchSize) field.

This limit prevents issues with oversized error messages. If a group exceeds this [limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Write-Command-Batch-Limit-Size), the client driver divides the group into smaller groups with counts less than or equal to the value of the limit. For example, with the `maxWriteBatchSize` value of `100,000`, if the queue consists of `200,000` operations, the driver creates 2 groups, each with `100,000` operations.

**Note:**

The driver only divides the group into smaller groups when using the high-level API. If using [`db.runCommand()`](https://www.mongodb.com/docs/manual/reference/method/db.runcommand.md#mongodb-method-db.runCommand) directly (for example, when writing a driver), MongoDB throws an error when attempting to execute a write batch which exceeds the limit.

If the error report for a single batch grows too large, MongoDB truncates all remaining error messages to the empty string. If there are at least two error messages with total size greater than `1MB`, they are trucated.

The sizes and grouping mechanics are internal performance details and are subject to change in future versions.

Executing an [`ordered`](https://www.mongodb.com/docs/manual/reference/method/db.collection.initializeorderedbulkop.md#mongodb-method-db.collection.initializeOrderedBulkOp) list of operations on a sharded collection will generally be slower than executing an [`unordered`](https://www.mongodb.com/docs/manual/reference/method/db.collection.initializeunorderedbulkop.md#mongodb-method-db.collection.initializeUnorderedBulkOp) list since with an ordered list, each operation must wait for the previous operation to finish.

### Capped Collections

`bulkWrite()` has restrictions on [capped collections:](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-capped-collection)

- `updateOne` and `updateMany` throw a `WriteError` if the update increases the document size.

- `replaceOne` throws a `WriteError` if the replacement document is larger than the original.

- `deleteOne` and `deleteMany` throw a `WriteError` on capped collections.

### Error Handling

`bulkWrite()` throws a `BulkWriteError` exception on errors. See [Error Handling inside Transactions.](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-error-handling-txn)

Excluding [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-write-concern) errors, ordered operations stop after an error, while unordered operations continue to process any remaining write operations in the queue, unless when run inside a transaction. See [Error Handling inside Transactions.](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkwrite-error-handling-txn)

Write concern errors are displayed in the `writeConcernErrors` field, while all other errors are displayed in the `writeErrors` field. If an error is encountered, the number of successful write operations are displayed instead of the inserted `_id` values. Ordered operations display the single error encountered while unordered operations display each error in an array.

#### Schema Validation Errors

If your collection uses [schema validation](https://www.mongodb.com/docs/manual/core/schema-validation.md#std-label-schema-validation-overview) and has `validationAction` set to `error`, inserting an invalid document or updating a document with invalid values throws an error. Operations preceding the invalid operation in the `operations` array are executed and written to the collection. The `ordered` field determines if the remaining operations are executed.

### Transactions

`bulkWrite()` can be used inside [distributed transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions)

**Important:**

In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, the [denormalized data model (embedded documents and arrays)](https://www.mongodb.com/docs/manual/data-modeling/embedding.md#std-label-data-modeling-embedding) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for distributed transactions.

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also [Production Considerations.](https://www.mongodb.com/docs/manual/core/transactions-production-consideration.md#std-label-production-considerations)

#### Inserts and Upserts within Transactions

For [feature compatibility version (fcv)](https://www.mongodb.com/docs/manual/reference/command/setfeaturecompatibilityversion.md#std-label-view-fcv) `"4.4"` and greater, if an insert operation or update operation with `upsert: true` is run in a transaction against a non-existing collection, the collection is implicitly created.

**Note:**

You cannot create new collections in cross-shard write transactions. For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.

#### Write Concerns and Transactions

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see [Transactions and Write Concern.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-write-concern)

#### Error Handling inside Transactions

Starting in MongoDB 4.2, if a [`db.collection.bulkWrite()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#mongodb-method-db.collection.bulkWrite) operation encounters an error inside a [transaction](https://www.mongodb.com/docs/manual/core/transactions.md), the method throws a [BulkWriteException](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#std-label-bulkWrite-error-handling) (same as outside a transaction).

In 4.0, if the `bulkWrite` operation encounters an error inside a transaction, the error thrown is not wrapped as a `BulkWriteException`.

Inside a transaction, the first error in a bulk write causes the entire bulk write to fail and aborts the transaction, even if the bulk write is unordered.

## Examples

### Ordered Bulk Write Example

It is important that you understand `bulkWrite()` operation ordering and error handling. By default, `bulkWrite()` runs an ordered list of operations:

- Operations run serially.

- If an operation has an error, that operation and any following operations are not run.

- Operations listed before the error operation are completed.

The `bulkWrite()` examples use the `pizzas` collection:

```javascript
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 }
] )
```

The following [`db.collection.bulkWrite()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#mongodb-method-db.collection.bulkWrite) example runs the following operations on the `pizzas` collection:

- Adds two documents using `insertOne`.

- Updates a document using `updateOne`.

- Deletes a document using `deleteOne`.

- Replaces a document using `replaceOne`.

```javascript
try {
   db.pizzas.bulkWrite( [
      { insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
      { insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } },
      { updateOne: {
         filter: { type: "cheese" },
         update: { $set: { price: 8 } }
      } },
      { deleteOne: { filter: { type: "pepperoni"} } },
      { replaceOne: {
         filter: { type: "vegan" },
         replacement: { type: "tofu", size: "small", price: 4 }
      } }
   ] )
} catch( error ) {
   print( error )
}
```

Example output, which includes a summary of the completed operations:

```javascript
{
   acknowledged: true,
   insertedCount: 2,
   insertedIds: { '0': 3, '1': 4 },
   matchedCount: 2,
   modifiedCount: 2,
   deletedCount: 1,
   upsertedCount: 0,
   upsertedIds: {}
}
```

If the collection already contained a document with an `_id` of `4` before running the previous `bulkWrite()` example, the following duplicate key exception is returned for the second `insertOne` operation:

```javascript
writeErrors: [
   WriteError {
      err: {
         index: 1,
         code: 11000,
         errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
         op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
      }
   }
],
result: BulkWriteResult {
   result: {
      ok: 1,
      writeErrors: [
         WriteError {
            err: {
               index: 1,
               code: 11000,
               errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
               op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
            }
         }
      ],
      writeConcernErrors: [],
      insertedIds: [ { index: 0, _id: 3 }, { index: 1, _id: 4 } ],
      nInserted: 1,
      nUpserted: 0,
      nMatched: 0,
      nModified: 0,
      nRemoved: 0,
      upserted: []
   }
}
```

Because the `bulkWrite()` example is ordered, only the first `insertOne` operation is completed.

To complete all operations that do not have errors, run `bulkWrite()` with `ordered` set to `false`. For an example, see the following section.

### Unordered Bulk Write Example

To specify an unordered `bulkWrite()`, set `ordered` to `false`.

In an unordered `bulkWrite()` list of operations:

- Operations can run in parallel (not guaranteed). For details. See [Ordered vs Unordered Operations.](https://www.mongodb.com/docs/manual/core/bulk-write-operations.md#std-label-bulk-write-operations-ordered-vs-unordered)

- Operations with errors are not completed.

- All operations without errors are completed.

Continuing the `pizzas` collection example, drop and recreate the collection:

```javascript
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 }
] )
```

In the following example:

- `bulkWrite()` runs unordered operations on the `pizzas` collection.

- The second `insertOne` operation has the same `_id` as the first `insertOne`, which causes a duplicate key error.

```javascript
try {
   db.pizzas.bulkWrite( [
      { insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
      { insertOne: { document: { _id: 3, type: "sausage", size: "large", price: 10 } } },
      { updateOne: {
         filter: { type: "cheese" },
         update: { $set: { price: 8 } }
      } },
      { deleteOne: { filter: { type: "pepperoni"} } },
      { replaceOne: {
         filter: { type: "vegan" },
         replacement: { type: "tofu", size: "small", price: 4 }
      } }
   ],
   { ordered: false } )
} catch( error ) {
   print( error )
}
```

Example output, which includes the duplicate key error and a summary of the completed operations:

```javascript
writeErrors: [
   WriteError {
      err: {
         index: 1,
         code: 11000,
         errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 3 }',
         op: { _id: 3, type: 'sausage', size: 'large', price: 10 }
      }
   }
],
result: BulkWriteResult {
   result: {
      ok: 1,
      writeErrors: [
         WriteError {
            err: {
               index: 1,
               code: 11000,
               errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 3 }',
               op: { _id: 3, type: 'sausage', size: 'large', price: 10 }
            }
         }
      ],
      writeConcernErrors: [],
      insertedIds: [ { index: 0, _id: 3 }, { index: 1, _id: 3 } ],
      nInserted: 1,
      nUpserted: 0,
      nMatched: 2,
      nModified: 2,
      nRemoved: 1,
      upserted: []
   }
}
```

The second `insertOne` operation fails because of the duplicate key error. In an unordered `bulkWrite()`, any operation without an error is completed.

### Write Concern Errors in Sharded Clusters

**Changed in version 8.1.2**

When `bulkWrite()` executes on [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-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.

### Bulk Write with Write Concern Example

Continuing the `pizzas` collection example, drop and recreate the collection:

```javascript
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 }
] )
```

The following `bulkWrite()` example runs operations on the `pizzas` collection and sets a `"majority"` [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-w) with a 100 millisecond [timeout:](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-wtimeout)

```javascript
try {
   db.pizzas.bulkWrite( [
      { updateMany: {
         filter: { size: "medium" },
         update: { $inc: { price: 0.1 } }
      } },
      { updateMany: {
         filter: { size: "small" },
         update: { $inc: { price: -0.25 } }
      } },
      { deleteMany: { filter: { size: "large" } } },
      { insertOne: {
         document: { _id: 4, type: "sausage", size: "small", price: 12 }
      } } ],
      { writeConcern: { w: "majority", wtimeout: 100 } }
   )
} catch( error ) {
   print( error )
}
```

If the time for the majority of replica set members to acknowledge the operations exceeds `wtimeout`, the example returns a write concern error and a summary of completed operations:

```javascript
result: BulkWriteResult {
   result: {
      ok: 1,
      writeErrors: [],
      writeConcernErrors: [
         WriteConcernError {
            err: {
               code: 64,
               codeName: 'WriteConcernTimeout',
               errmsg: 'waiting for replication timed out',
               errInfo: { wtimeout: true, writeConcern: [Object] }
            }
         }
      ],
      insertedIds: [ { index: 3, _id: 4 } ],
      nInserted: 0,
      nUpserted: 0,
      nMatched: 2,
      nModified: 2,
      nRemoved: 0,
      upserted: [],
      opTime: { ts: Timestamp({ t: 1660329086, i: 2 }), t: Long("1") }
   }
}
```
