> This page location: /docs.md > /docs/drivers.md > /docs/languages/python.md > /docs/languages/python/pymongo-driver/current.md > /docs/languages/python/pymongo-driver/current/crud.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: sync, async
-->

# Bulk Write Operations

## Overview

In this guide, you can learn how to use PyMongo to perform **bulk operations**. Bulk operations reduce the number of calls to the server by performing multiple write operations in a single method.

The `Collection` and `MongoClient` classes both provide a `bulk_write()` method. When calling `bulk_write()` on a `Collection` instance, you can perform multiple write operations on a single collection. When calling `bulk_write()` on a `MongoClient` instance, you can perform bulk writes across multiple namespaces. In MongoDB, a namespace consists of the database name and the collection name in the format `<database>.<collection>`.

**Important:**

To perform bulk operations on a `MongoClient` instance, ensure that your application meets the following requirements:

- Uses PyMongo v4.9 or later

- Connects to MongoDB Server v8.0 or later

### Sample Data

The examples in this guide use the `sample_restaurants.restaurants` and `sample_mflix.movies` collections from the [Atlas sample datasets](https://www.mongodb.com/docs/atlas/sample-data/). To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the [Get Started with PyMongo](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started.md#std-label-pymongo-get-started) tutorial.

## Define the Write Operations

For each write operation you want to perform, create an instance of one of the following operation classes:

- `InsertOne`

- `UpdateOne`

- `UpdateMany`

- `ReplaceOne`

- `DeleteOne`

- `DeleteMany`

Then, pass a list of these instances to the `bulk_write()` method.

**Important:**

Ensure that you import the write operation classes into your application file, as shown in the following code:

```python
from pymongo import InsertOne, UpdateOne, UpdateMany, ReplaceOne, DeleteOne, DeleteMany
```

The following sections show how to create instances of the preceding classes, which you can use to perform collection and client bulk operations.

### Insert Operations

To perform an insert operation, create an instance of `InsertOne` and specify the document you want to insert. Pass the following keyword arguments to the `InsertOne` constructor:

- `namespace`: The namespace in which to insert the document. This argument is optional if you perform the bulk operation on a single collection.

- `document`: The document to insert.

The following example creates an instance of `InsertOne`:

```python
operation = InsertOne(
    namespace="sample_restaurants.restaurants",
    document={
        "name": "Mongo's Deli",
        "cuisine": "Sandwiches",
        "borough": "Manhattan",
        "restaurant_id": "1234"
    }
)
```

You can also create an instance of `InsertOne` by passing an instance of a custom class to the constructor. This provides additional type safety if you're using a type-checking tool. The instance you pass must inherit from the `TypedDict` class.

**Note: TypedDict in Python 3.7 and Earlier**

The [TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict) class is in the `typing` module, which is available only in Python 3.8 and later. To use the `TypedDict` class in earlier versions of Python, install the [typing\_extensions](https://pypi.org/project/typing-extensions/) package.

The following example constructs an `InsertOne` instance by using a custom class for added type safety:

```python
class Restaurant (TypedDict):
    name: str
    cuisine: str
    borough: str
    restaurant_id: str

operation = pymongo.InsertOne(Restaurant(
    name="Mongo's Deli", cuisine="Sandwiches", borough="Manhattan", restaurant_id="1234"))
```

To insert multiple documents, create an instance of `InsertOne` for each document.

**Note: \_id Field Must Be Unique**

In a MongoDB collection, each document must contain an `_id` field with a unique value.

If you specify a value for the `_id` field, you must ensure that the value is unique across the collection. If you don't specify a value, the driver automatically generates a unique `ObjectId` value for the field.

We recommend letting the driver automatically generate `_id` values to ensure uniqueness. Duplicate `_id` values violate unique index constraints, which causes the driver to return an error.

### Update Operations

To update a document, create an instance of `UpdateOne` and pass in the following arguments:

- `namespace`: The namespace in which to perform the update. This argument is optional if you perform the bulk operation on a single collection.

- `filter`: The **query filter** that specifies the criteria used to match documents in your collection.

- `update`: The update you want to perform. For more information about update operations, see the [Field Update Operators](https://www.mongodb.com/docs/manual/reference/operator/update-field/) guide in the MongoDB Server manual.

`UpdateOne` updates *the first* document that matches your query filter.

The following example creates an instance of `UpdateOne`:

```python
operation = UpdateOne(
    namespace="sample_restaurants.restaurants",
    filter={ "name": "Mongo's Deli" },
    update={ "$set": { "cuisine": "Sandwiches and Salads" }}
)
```

To update multiple documents, create an instance of `UpdateMany` and pass in the same arguments. `UpdateMany` updates *all* documents that match your query filter.

The following example creates an instance of `UpdateMany`:

```python
operation = UpdateMany(
    namespace="sample_restaurants.restaurants",
    filter={ "name": "Mongo's Deli" },
    update={ "$set": { "cuisine": "Sandwiches and Salads" }}
)
```

### Replace Operations

A replace operation removes all fields and values of a specified document and replaces them with new ones. To perform a replace operation, create an instance of `ReplaceOne` and pass in the following arguments:

- `namespace`: The namespace in which to perform the replace operation. This argument is optional if you perform the bulk operation on a single collection.

- `filter`: The **query filter** that specifies the criteria used to match the document to replace.

- `replacement`: The document that includes the new fields and values you want to store in the matching document.

The following example creates an instance of `ReplaceOne`:

```python
operation = ReplaceOne(
    namespace="sample_restaurants.restaurants",
    filter={ "restaurant_id": "1234" },
    replacement={
        "name": "Mongo's Pizza",
        "cuisine": "Pizza",
        "borough": "Brooklyn",
        "restaurant_id": "5678"
    }
)
```

You can also create an instance of `ReplaceOne` by passing an instance of a custom class to the constructor. This provides additional type safety if you're using a type-checking tool. The instance you pass must inherit from the `TypedDict` class.

**Note: TypedDict in Python 3.7 and Earlier**

The [TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict) class is in the `typing` module, which is available only in Python 3.8 and later. To use the `TypedDict` class in earlier versions of Python, install the [typing\_extensions](https://pypi.org/project/typing-extensions/) package.

The following example constructs a `ReplaceOne` instance by using a custom class for added type safety:

```python
class Restaurant (TypedDict):
    name: str
    cuisine: str
    borough: str
    restaurant_id: str

operation = pymongo.ReplaceOne(
    { "restaurant_id": "1234" },
    Restaurant(name="Mongo's Pizza", cuisine="Pizza", borough="Brooklyn", restaurant_id="5678")
)
```

To replace multiple documents, you must create an instance of `ReplaceOne` for each document.

**Tip: Type-Checking Tools**

To learn more about type-checking tools available for Python, see [Type Checkers](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/integrations.md#std-label-pymongo-tools-type-checkers) on the Tools page.

### Delete Operations

To delete a document, create an instance of `DeleteOne` and pass in the following arguments:

- `namespace`: The namespace in which to delete the document. This argument is optional if you perform the bulk operation on a single collection.

- `filter`: The **query filter** that specifies the criteria used to match the document to delete.

`DeleteOne` removes only *the first* document that matches your query filter.

The following example creates an instance of `DeleteOne`:

```python
operation = DeleteOne(
    namespace="sample_restaurants.restaurants",
    filter={ "restaurant_id": "5678" }
)
```

To delete multiple documents, create an instance of `DeleteMany` and pass in a namespace and query filter specifying the document you want to delete. `DeleteMany` removes *all* documents that match your query filter.

The following example creates an instance of `DeleteMany`:

```python
operation = DeleteMany(
    namespace="sample_restaurants.restaurants",
    filter={ "name": "Mongo's Deli" }
)
```

## Call the bulk\_write() Method

After you define a class instance for each operation you want to perform, pass a list of these instances to the `bulk_write()` method. Call the `bulk_write()` method on a `Collection` instance to write to a single collection or a `MongoClient` instance to write to multiple namespaces.

If any of the write operations called on a `Collection` fail, PyMongo raises a `BulkWriteError` and does not perform any further operations. `BulkWriteError` provides a `details` attribute that includes the operation that failed, and details about the exception.

If any of the write operations called on a `MongoClient` fail, PyMongo raises a `ClientBulkWriteException` and does not perform any further operations. `ClientBulkWriteException` provides an `error` attribute that includes information about the exception.

**Note:**

When PyMongo runs a bulk operation, it uses the `write_concern` of the collection or client on which the operation is running. You can also set a write concern for the operation when using the `MongoClient.bulk_write()` method. The driver reports all write concern errors after attempting all operations, regardless of execution order.

To learn more about write concerns, see [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern/) in the MongoDB Server manual.

### Collection Bulk Write Example

The following example performs multiple write operations on the `restaurants` collection by using the `bulk_write()` method on a `Collection` instance. Select the Synchronous or Asynchronous tab to see the corresponding code:

### Synchronous

```python
operations = [
    InsertOne(
        document={
            "name": "Mongo's Deli",
            "cuisine": "Sandwiches",
            "borough": "Manhattan",
            "restaurant_id": "1234"
        }
    ),
    InsertOne(
        document={
            "name": "Mongo's Deli",
            "cuisine": "Sandwiches",
            "borough": "Brooklyn",
            "restaurant_id": "5678"
        }
    ),
    UpdateMany(
        filter={ "name": "Mongo's Deli" },
        update={ "$set": { "cuisine": "Sandwiches and Salads" }}
    ),
    DeleteOne(
        filter={ "restaurant_id": "1234" }
    )
]

results = restaurants.bulk_write(operations)

print(results)
```

**Output:**

```text
BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2,
'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []},
acknowledged=True)
```

### Client Bulk Write Example

The following example performs multiple write operations on the `sample_restaurants.restaurants` and `sample_mflix.movies` namespaces by using the `bulk_write()` method on a `MongoClient` instance. Select the Synchronous or Asynchronous tab to see the corresponding code:

### Synchronous

```python
operations = [
    InsertOne(
        namespace="sample_mflix.movies",
        document={
            "title": "Minari",
            "runtime": 217,
            "genres": ["Drama", "Comedy"]
        }
    ),
    UpdateOne(
        namespace="sample_mflix.movies",
        filter={ "title": "Minari" },
        update={ "$set": { "runtime": 117 }}
    ),
    DeleteMany(
        namespace="sample_restaurants.restaurants",
        filter={ "cuisine": "French" }
    )
]

results = client.bulk_write(operations)

print(results)
```

**Output:**

```text
ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [],
'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1,
'nModified': 1, 'nDeleted': 344, 'insertResults': {}, 'updateResults': {},
'deleteResults': {}}, acknowledged=True, verbose=False)
```

## Customize Bulk Write Operations

The `bulk_write()` method optionally accepts additional parameters, which represent options you can use to configure the bulk write operation.

### Collection Bulk Write Options

The following table describes the options you can pass to the `Collection.bulk_write()` method:

| Property | Description |
| --- | --- |
| `ordered` | If `True`, the driver performs the write operations in the order provided. If an error occurs, the remaining operations are not attempted.If `False`, the driver performs the operations in an arbitrary order and attempts to perform all operations.Defaults to `True`. |
| `bypass_document_validation` | Specifies whether the operation bypasses document-level validation. For more information, see [Schema Validation](https://www.mongodb.com/docs/manual/core/schema-validation/#schema-validation) in the MongoDB Server manual.Defaults to `False`. |
| `session` | An instance of `ClientSession`. For more information, see the [API documentation](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/client_session.html#pymongo.client_session.ClientSession). |
| `comment` | A comment to attach to the operation. For more information, see the [delete command fields](https://www.mongodb.com/docs/manual/reference/command/delete/#command-fields) guide in the MongoDB Server manual. |
| `let` | A map of parameter names and values. Values must be constant or closed expressions that don't reference document fields. For more information, see the [let statement](https://www.mongodb.com/docs/manual/reference/command/delete/#std-label-delete-let-syntax) in the MongoDB Server manual. |

The following example calls the `bulk_write()` method from the preceding [Collection Bulk Write Example](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write.md#std-label-pymongo-bulk-write-collection-ex) but sets the `ordered` option to `False`. Select the Synchronous or Asynchronous tab to see the corresponding code:

### Synchronous

```python
results = restaurants.bulk_write(operations, ordered=False)
```

If any of the write operations in an unordered bulk write fail, PyMongo reports the errors only after attempting all operations.

**Note:**

Unordered bulk operations do not guarantee order of execution. The order can differ from the way you list them to optimize the runtime.

### Client Bulk Write Options

The following table describes the options you can pass to the `MongoClient.bulk_write()` method:

| Property | Description |
| --- | --- |
| `session` | An instance of `ClientSession`. For more information, see the [API documentation](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/client_session.html#pymongo.client_session.ClientSession). |
| `ordered` | If `True`, the driver performs the write operations in the order provided. If an error occurs, the remaining operations are not attempted.If `False`, the driver performs the operations in an arbitrary order and attempts to perform all operations.Defaults to `True`. |
| `verbose_results` | Specifies whether the operation returns detailed results for each successful operation.Defaults to `False`. |
| `bypass_document_validation` | Specifies whether the operation bypasses document-level validation. For more information, see [Schema Validation](https://www.mongodb.com/docs/manual/core/schema-validation/#schema-validation) in the MongoDB Server manual.Defaults to `False`. |
| `comment` | A comment to attach to the operation. For more information, see the [delete command fields](https://www.mongodb.com/docs/manual/reference/command/delete/#command-fields) guide in the MongoDB Server manual. |
| `let` | A map of parameter names and values. Values must be constant or closed expressions that don't reference document fields. For more information, see the [let statement](https://www.mongodb.com/docs/manual/reference/command/delete/#std-label-delete-let-syntax) in the MongoDB Server manual. |
| `write_concern` | Specifies the write concern to use for the bulk operation. For more information, see [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern/) in the MongoDB Server manual. |

The following example calls the `bulk_write()` method from the preceding [Client Bulk Write Example](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write.md#std-label-pymongo-bulk-write-client-ex) but sets the `verbose_results` option to `True`. Select the Synchronous or Asynchronous tab to see the corresponding code:

### Synchronous

```python
results = client.bulk_write(operations, verbose_results=True)
```

**Output:**

```text
ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [],
'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, 'nModified': 1,
'nDeleted': 344, 'insertResults': {0: InsertOneResult(ObjectId('...'),
acknowledged=True)}, 'updateResults': {1: UpdateResult({'ok': 1.0, 'idx': 1, 'n': 1,
'nModified': 1}, acknowledged=True)}, 'deleteResults': {2: DeleteResult({'ok': 1.0,
'idx': 2, 'n': 344}, acknowledged=True)}}, acknowledged=True, verbose=True)
```

## Return Values

This section describes the return value of the following bulk operation methods:

- [Collection.bulk\_write()](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write.md#std-label-pymongo-bulk-write-collection-return)

- [MongoClient.bulk\_write()](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write.md#std-label-pymongo-bulk-write-client-return)

### Collection Bulk Write Return Value

The `Collection.bulk_write()` method returns a `BulkWriteResult` object. The `BulkWriteResult` object contains the following properties:

| Property | Description |
| --- | --- |
| `acknowledged` | Indicates if the server acknowledged the write operation. |
| `bulk_api_result` | The raw bulk API result returned by the server. |
| `deleted_count` | The number of documents deleted, if any. |
| `inserted_count` | The number of documents inserted, if any. |
| `matched_count` | The number of documents matched for an update, if applicable. |
| `modified_count` | The number of documents modified, if any. |
| `upserted_count` | The number of documents upserted, if any. |
| `upserted_ids` | A map of the operation's index to the `_id` of the upserted documents, if applicable. |

### Client Bulk Write Return Value

The `MongoClient.bulk_write()` method returns a `ClientBulkWriteResult` object. The `ClientBulkWriteResult` object contains the following properties:

| Property | Description |
| --- | --- |
| `acknowledged` | Indicates if the server acknowledged the write operation. |
| `bulk_api_result` | The raw bulk API result returned by the server. |
| `delete_results` | A map of any successful delete operations and their results. |
| `deleted_count` | The number of documents deleted, if any. |
| `has_verbose_results` | Indicates whether the returned results are verbose. |
| `insert_results` | A map of any successful insert operations and their results. |
| `inserted_count` | The number of documents inserted, if any. |
| `matched_count` | The number of documents matched for an update, if applicable. |
| `modified_count` | The number of documents modified, if any. |
| `update_results` | A map of any successful update operations and their results. |
| `upserted_count` | The number of documents upserted, if any. |

## Troubleshooting

### Client Type Annotations

If you don't add a type annotation for your `MongoClient` object, your type checker might show an error similar to the following:

```python
from pymongo import MongoClient
client = MongoClient()  # error: Need type annotation for "client"
```

The solution is to annotate the `MongoClient` object as `client: MongoClient` or `client: MongoClient[Dict[str, Any]]`.

### Incompatible Type

If you specify `MongoClient` as a type hint but don't include data types for the document, keys, and values, your type checker might show an error similar to the following:

```python
error: Dict entry 0 has incompatible type "str": "int";
expected "Mapping[str, Any]": "int"
```

The solution is to add the following type hint to your `MongoClient` object:

```python
client: MongoClient[Dict[str, Any]]
```

## Additional Information

To learn how to perform individual write operations, see the following guides:

- [Insert Documents](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert.md#std-label-pymongo-write-insert)

- [Update Documents](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/update.md#std-label-pymongo-write-update)

- [Replace Documents](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/replace.md#std-label-pymongo-write-replace)

- [Delete Documents](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/delete.md#std-label-pymongo-write-delete)

### API Documentation

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

- [Collection.bulk\_write()](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write)

- [MongoClient.bulk\_write()](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.bulk_write)

- [InsertOne](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.InsertOne)

- [UpdateOne](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.UpdateOne)

- [UpdateMany](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.UpdateMany)

- [ReplaceOne](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.ReplaceOne)

- [DeleteOne](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.DeleteOne)

- [DeleteMany](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/operations.html#pymongo.operations.DeleteMany)

- [BulkWriteResult](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/results.html#pymongo.results.BulkWriteResult)

- [ClientBulkWriteResult](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/results.html#pymongo.results.ClientBulkWriteResult)

- [BulkWriteError](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/errors.html#pymongo.errors.BulkWriteError)

- [ClientBulkWriteException](https://pymongo.readthedocs.io/en/4.19.0/api/pymongo/errors.html#pymongo.errors.ClientBulkWriteException)
