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

Make identity enforceable.

Match indexes to queries and enforce a meaningful uniqueness rule.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

An index can support filtering and ordering without scanning every document, but it adds storage and write maintenance. A unique index also enforces an identity rule at the database boundary, protecting against concurrent inserts. Compound index order matters for supported query patterns. Inspect actual plans and representative workloads instead of assuming that creating an index guarantees faster queries.

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

with mongo_lab() as collection:
    from pymongo.errors import DuplicateKeyError
    collection.create_index([("project", 1), ("name", 1)], unique=True, name="project_name_unique")
    try:
        collection.insert_one({"_id": 9, "project": "Orbit", "name": "Build", "minutes": 1})
    except DuplicateKeyError:
        print("Duplicate project/name rejected")
    print("project_name_unique" in collection.index_information())
↳ EXPECTED OUTPUT
Duplicate project/name rejected
True

03 Under the hood

  1. 1

    The existing fixture contains unique project/name pairs. A unique index cannot be built successfully if existing documents already violate its rule.

  2. 2

    The rejected document has a different _id but repeats the indexed identity. This illustrates why application-side check-then-insert is not enough under concurrency.

  3. 3

    Missing values and nulls have index semantics that may be surprising. For optional identifiers, consider whether a partial index with a specific filter expresses the intended constraint.

04 Your turn, builder

A SMALL MISSION

Create a nonunique index on done then minutes, and verify its metadata.

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

with mongo_lab() as collection:
    collection.create_index([("done", 1), ("minutes", -1)], name="state_duration")
    print("state_duration" in collection.index_information())

05 Check your signal

QUICK SIGNAL CHECK

Why use a unique index for an identity rule?

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.