Make identity enforceable.
Match indexes to queries and enforce a meaningful uniqueness rule.
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.
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())Duplicate project/name rejected True
03 Under the hood
- 1
The existing fixture contains unique project/name pairs. A unique index cannot be built successfully if existing documents already violate its rule.
- 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
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
Create a nonunique index on done then minutes, and verify its metadata.
Reveal one possible solution +
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
Why use a unique index for an identity rule?
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 ↗.