Model for the question you ask.
Choose document boundaries around access patterns and consistency requirements.
01 The idea
Embedding puts related data in one document, which can make a common read and a single-document atomic change straightforward. References keep entities separate when they grow independently or have a different lifecycle. Neither choice is universally correct. MongoDB transactions can coordinate multiple documents on supported replica-set or sharded deployments, but add operational and performance costs.
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:
client = collection.database.client
with client.start_session() as session:
with session.start_transaction():
collection.update_one({"_id": 2}, {"$inc": {"minutes": -10}}, session=session)
collection.update_one({"_id": 3}, {"$inc": {"minutes": 10}}, session=session)
for document in collection.find({"_id": {"$in": [2, 3]}}).sort("_id", 1):
print(document["name"], document["minutes"])Build 30 Test 30
03 Under the hood
- 1
The workbench initializes a single-node practice replica set specifically so this lesson can use sessions and transactions. A standalone server does not support this transaction workflow.
- 2
Every operation participating in the transaction receives session=session. Exiting the transaction block commits on success and aborts on an exception.
- 3
For a production retry strategy, PyMongo’s with_transaction callback can retry certain transaction and commit errors. A callback may execute more than once, so avoid irreversible external side effects inside it. Choose document boundaries that keep the most important invariants local when possible.
04 Your turn, builder
Demonstrate an embedded summary document with a bounded preferences object.
Reveal one possible solution +
from lab_support import mongo_lab
with mongo_lab() as collection:
collection.insert_one({"_id": 9, "name": "Orbit settings", "preferences": {"theme": "orange", "notifications": True}})
document = collection.find_one({"_id": 9})
print(document["preferences"]["theme"])05 Check your signal
What server topology does this transaction example require?
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 ↗.