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

A catalogue with a contract.

Combine validation, unique identities, updates, and a report behind a narrow interface.

ADVANCED LAB / BUILD PROJECT
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

This project treats a document catalogue as an application boundary rather than a bag of arbitrary dictionaries. A stable identity supports repeatable upserts, a unique index enforces that identity, and a projected sorted query returns only the fields a caller needs. Test the database contract with known records and preserve a distinction between no records and a failed server operation.

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_project.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    def save_task(collection, project, name, minutes):
        if not project.strip() or not name.strip() or type(minutes) is not int or minutes < 0:
            raise ValueError("Valid project, name and minutes required")
        collection.update_one({"project": project, "name": name}, {"$set": {"minutes": minutes}, "$setOnInsert": {"done": False}}, upsert=True)
    collection.create_index([("project", 1), ("name", 1)], unique=True)
    save_task(collection, "Atlas", "Document", 12)
    save_task(collection, "Atlas", "Document", 18)
    records = list(collection.find({"project": "Atlas"}, {"_id": 0, "name": 1, "minutes": 1}).sort("name", 1))
    print(records)
↳ EXPECTED OUTPUT
[{'name': 'Document', 'minutes': 18}, {'name': 'Review', 'minutes': 30}]

03 Under the hood

  1. 1

    The second save updates the same logical task rather than inserting a duplicate. The unique compound index protects that rule when more than one writer exists.

  2. 2

    The projection keeps generated ids and unrelated fields out of the result. Sorting by name makes this small report deterministic.

  3. 3

    For pagination, add a stable unique tie-breaker and a documented cursor. Add integration tests for duplicate identity, missing records, updates, and invalid input, not just the happy-path insert.

04 Your turn, builder

A SMALL MISSION

Build a function returning total unfinished minutes for one project, including zero for no matching records.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    def total_minutes(collection, project):
        pipeline = [{"$match": {"project": project, "done": False}}, {"$group": {"_id": None, "minutes": {"$sum": "$minutes"}}}]
        rows = list(collection.aggregate(pipeline))
        return rows[0]["minutes"] if rows else 0
    assert total_minutes(collection, "Missing") == 0
    print(total_minutes(collection, "Orbit"))

↗ Definition of done

  • □Validate required names and nonnegative integer durations.
  • □Enforce one task per project/name identity.
  • □Save the same task twice without duplicating it.
  • □Return projected, sorted results.
  • □Test no-match and server-failure paths separately.

05 Check your signal

QUICK SIGNAL CHECK

What makes the repeated save target one logical task?

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.