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

Change a field, not the whole story.

Use update operators deliberately and distinguish matched from modified records.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

mongodb_updates.py
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"])
↳ EXPECTED OUTPUT
1 1
45 True

03 Under the hood

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

    matched_count reports matching documents; modified_count reports actual changes. Assigning an existing value can match without modifying.

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

A SMALL MISSION

Upsert a task with a stable id and an insertion-only name.

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

QUICK SIGNAL CHECK

Why use $inc instead of a read-then-write increment?

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.