Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python meets MongoDB
EXPERIMENT 96 / 101

Model for the question you ask.

Choose document boundaries around access patterns and consistency requirements.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

mongodb_models.py
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"])
↳ EXPECTED OUTPUT
Build 30
Test 30

03 Under the hood

  1. 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. 2

    Every operation participating in the transaction receives session=session. Exiting the transaction block commits on success and aborts on an exception.

  3. 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

A SMALL MISSION

Demonstrate an embedded summary document with a bounded preferences object.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What server topology does this transaction example require?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.