Python PyMongo Update, Delete, and Bulk Operations
Learn how to perform update, delete, and bulk write operations with PyMongo, including syntax, update operators, error handling, and batching strategies.

PyMongo provides a direct API for updating and deleting MongoDB documents and for combining those operations into bulk writes. This article covers update_one(), update_many(), delete_one(), delete_many(), and bulk_write(), including the behavior of common update operators and the tradeoffs of each approach.
Core Update and Delete Methods
PyMongo exposes update_one(), update_many(), delete_one(), and delete_many() on Collection objects. Each method takes a filter and, for updates, a set of update operators. The _one variants affect at most one document, while the _many variants affect all matching documents.
from datetime import datetime, timedelta, timezone
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["inventory"]
collection = db["items"]
# Update the first document where sku is "ABC"
collection.update_one(
{"sku": "ABC"},
{"$set": {"price": 19.99}}
)
# Update all documents where category is "clearance"
collection.update_many(
{"category": "clearance"},
{"$mul": {"price": 0.8}}
)
# Delete one document with a specific id
collection.delete_one({"_id": 12345})
# Delete all documents older than a date
cutoff = datetime.now(timezone.utc) - timedelta(days=30)
collection.delete_many({"created_at": {"$lt": cutoff}})The filter uses the same query syntax as find(). An update document normally contains update operators such as $set, $unset, $inc, or $push. You can also pass a replacement document without operators, but that replaces the entire matched document and removes any fields not present in the replacement, so it is usually not what you want for partial updates.
Update Operators and Their Effects
Choosing the right operator is critical for correctness and atomicity. The table below summarizes the most common operators and their behavior.
| Operator | Effect | Example |
|---|---|---|
$set | Sets the value of a field | {"$set": {"status": "active"}} |
$unset | Removes a field | {"$unset": {"temp_field": ""}} |
$inc | Increments a numeric field by a given amount | {"$inc": {"count": 1}} |
$mul | Multiplies a numeric field | {"$mul": {"price": 1.1}} |
$push | Appends a value to an array field | {"$push": {"tags": "new"}} |
$pull | Removes all matching values from an array | {"$pull": {"tags": "obsolete"}} |
$rename | Renames a field | {"$rename": {"old": "new"}} |
When multiple operators appear in the same update document, MongoDB applies them in a single atomic operation. For example, you can increment a counter and update a timestamp together:
from datetime import datetime, timezone
collection.update_one(
{"_id": 1},
{"$inc": {"views": 1}, "$set": {"last_viewed": datetime.now(timezone.utc)}}
)This avoids the race condition that would occur if you issued two separate updates.
Bulk Write Operations with bulk_write()
For large sequences of updates and deletes, bulk_write() is the recommended approach. It accepts a list of write operations and executes them in fewer round trips than individual method calls. Operations are instances of UpdateOne, UpdateMany, DeleteOne, or DeleteMany from pymongo.
from pymongo import UpdateOne, DeleteMany
operations = [
UpdateOne({"sku": "ABC"}, {"$set": {"price": 24.99}}),
UpdateMany({"category": "clearance"}, {"$mul": {"price": 0.7}}),
DeleteMany({"status": "archived"})
]
result = collection.bulk_write(operations)By default, bulk_write() executes operations in order and stops on the first error. This is called an ordered bulk write. If you pass ordered=False, MongoDB may execute operations in any order. Use ordered bulk writes when operation order matters, such as when an update depends on a previous delete.
The result object contains counters like matched_count, modified_count, deleted_count, and upserted_count. These are useful for verifying that the expected number of documents were affected.
Handling Errors and Write Concerns
Write operations can fail for several reasons: network issues, duplicate key errors, or validation failures. PyMongo raises PyMongoError subclasses such as DuplicateKeyError, BulkWriteError, or OperationFailure. For bulk writes, BulkWriteError includes a details attribute with per-operation error information.
from pymongo.errors import BulkWriteError
try:
result = collection.bulk_write(operations)
except BulkWriteError as e:
print(f"Failed operations: {e.details['writeErrors']}")Write concern controls how MongoDB acknowledges writes. The default acknowledges that the primary received the operation. For stronger durability, you can configure w="majority" or set j=True; in PyMongo this is typically set at the client, database, or collection level, not per operation. In production, w="majority" is often preferred to avoid losing acknowledged writes during failover.
Performance and Batching Strategies
Individual update_one() or delete_one() calls each require a round trip to the server. When you need to modify many documents, using bulk_write() reduces network overhead and can improve throughput. However, very large batches can consume significant memory on the client and server. A common pattern is to chunk operations into batches of 500–1000.
def chunked_bulk_write(collection, operations, batch_size=500):
for i in range(0, len(operations), batch_size):
batch = operations[i:i + batch_size]
collection.bulk_write(batch, ordered=False)Unordered bulk writes give MongoDB more flexibility to execute independent operations without enforcing an order, which can improve performance when order does not matter. Be aware that unordered writes do not guarantee that all operations succeed; if one fails, the others continue. Check the result to see how many succeeded.
Choosing the Right Approach for Your Workload
The decision between individual methods and bulk_write() depends on the number of operations and whether they are independent. For a single update or delete, use the dedicated method. For a few operations that must be ordered, individual calls are simpler to read. For large batches of independent changes, bulk_write() with ordered=False is the most efficient choice.
Another consideration is atomicity. A single update_one() is atomic at the document level, but a sequence of separate updates is not. If you need all-or-nothing behavior across multiple documents, you must use a transaction (available with replica sets) or design your data model to avoid the need.
Finally, always check the result of write operations. The modified_count may be lower than matched_count if the update does not change any fields. This is normal and often indicates that the data already matches the desired state. Relying on modified_count for business logic can lead to subtle bugs, so prefer matched_count when you only need to know that the filter matched a document.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.