Change a field, not the whole story.
Use update operators deliberately and distinguish matched from modified records.
01 The idea
An update operator changes selected fields while preserving the rest of the document. $set assigns values; $inc adjusts a numeric value atomically within a single document. update_one limits the operation to one matched document. Upsert creates a document if none matches, which is useful only when the matching identity and insertion contract are deliberate.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from lab_support import mongo_lab
with mongo_lab() as collection:
result = collection.update_one({"_id": 2}, {"$inc": {"minutes": 5}, "$set": {"done": True}})
print(result.matched_count, result.modified_count)
document = collection.find_one({"_id": 2})
print(document["minutes"], document["done"])1 1 45 True
03 Under the hood
- 1
The server applies both field operations as one single-document update. Reading a value in Python and writing a new value later would introduce a race for concurrent increments.
- 2
matched_count reports matching documents; modified_count reports actual changes. Assigning an existing value can match without modifying.
- 3
For optimistic concurrency, include an expected version in the filter and increment that version in the same update. A zero match then indicates a missing or changed record that the application must handle.
04 Your turn, builder
Upsert a task with a stable id and an insertion-only name.
Reveal one possible solution +
from lab_support import mongo_lab
with mongo_lab() as collection:
collection.update_one({"_id": 9}, {"$set": {"done": False}, "$setOnInsert": {"name": "New task", "minutes": 10}}, upsert=True)
print(collection.find_one({"_id": 9})["name"])05 Check your signal
Why use $inc instead of a read-then-write increment?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.