Python Tutorial
Python MongoDB - Update
Modify documents with update operators, and insert-or-update with upsert.
update_one With $set
Updates take two documents: a filter to find rows and an update describing the change. Always use an operator like $set — passing a plain document would replace the whole thing.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
customers = client["mydatabase"]["customers"]
result = customers.update_one(
{"address": "Valley 345"}, # filter
{"$set": {"address": "Canyon 123"}}) # update
print(result.modified_count, "document(s) modified")Forgetting $set — e.g. update_one(filter, {"address": "x"}) — is an error in modern PyMongo. Use an update operator, not a bare document (that is what replace_one is for).
update_many
result = customers.update_many(
{"address": {"$regex": "^S"}},
{"$set": {"region": "south"}})
print(result.modified_count, "documents updated")Common Update Operators
| Operator | Effect |
|---|---|
| $set | Set a field's value |
| $unset | Remove a field |
| $inc | Increment a number |
| $push / $pull | Add / remove an array element |
| $rename | Rename a field |
products = client["shop"]["products"]
products.update_one({"_id": 1}, {"$inc": {"stock": -1}}) # decrement
products.update_one({"_id": 1}, {"$push": {"tags": "sale"}}) # add to array
products.update_one({"_id": 1}, {"$unset": {"discount": ""}}) # remove fieldUpsert: Insert If Missing
With upsert=True, an update that matches nothing inserts a new document instead.
result = client["app"]["settings"].update_one(
{"user_id": 7},
{"$set": {"theme": "dark"}},
upsert=True)
if result.upserted_id:
print("Inserted new document:", result.upserted_id)
else:
print("Updated existing:", result.modified_count)replace_one vs update_one
replace_one swaps the entire matched document (except _id) for a new one — use it when you really mean to overwrite, not patch.
customers.replace_one(
{"name": "John"},
{"name": "John", "address": "New 1", "vip": True}) # full replacementBest Practices
- Always use update operators (
$set,$inc, …); usereplace_oneonly for full overwrites. $incand array operators are atomic — safe under concurrency.- Use
upsert=Truefor clean insert-or-update logic. - Check
modified_count/upserted_idto confirm what happened.
Try It Yourself
Exercise 1: Increase the views field of one document by 1.
Show solution
coll.update_one({"_id": 1}, {"$inc": {"views": 1}})Exercise 2: What is the difference between update_one with $set and replace_one?
Show solution
$set changes only the named fields; replace_one swaps the entire document (except _id).
📘 Real-World Deep Dive
Knowing <strong>MongoDB Update (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Update that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
db = MongoClient().shop
db.users.update_many({"active": False}, {"$set": {"archived": True}})
print("done")Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Update as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.