Access Patterns First: Modeling Documents
Design the trip documents of a ride-hailing app from its access patterns: embed what is bounded and read together, reference what grows, snapshot what must not change, validate the shape, and prove an equality-sort-range index with explain().
Contentsand lesson path
On this page
- The problem
- Step 1: Write the access patterns down
- Step 2: Decide embed or reference, field by field
- Step 3: Snapshot what must not change, and validate the shape
- Step 4: Index the main query and prove it with explain()
- Check your understanding
- Apply it
- Review prompt
Lessons of NoSQL Data Modeling
- Four NoSQL Families and the Trade-offs They Make Concept · 20 min
- Access Patterns First: Modeling Documents Worked example · 30 min
- Partition Keys and Clustering in Wide-Column Stores Concept · 25 min
- Lab: One Workload, Two Data Models Lab · 30 min
- Lab: Flattening Nested Documents for Analytics Lab · 20 min
- Check: Choose and Defend a Data Store Knowledge check · 8 questions
What you will learn
- Design a document schema from access patterns, choosing between embedding and referencing and adding indexes for the main queries.
01. The problem
In a relational design you normalise first and write queries later. In a document store the shape of each document decides which reads are cheap, so you start from the application's questions, its access patterns.
The task: design MongoDB collections for the riders, drivers and trips of the ride-hailing app, so that each main screen needs one indexed query. You will measure document sizes, enforce a schema and use explain() to check what the main query reads.
Tested with MongoDB 7.0 in Docker, Python 3.12 and PyMongo 4.20. Start a disposable server and a virtual environment; the scripts read the server address from MONGO_URL and default to mongodb://localhost:27017.
docker run -d --name nosql-mongo -p 27017:27017 mongo:7
mkdir doc-model && cd doc-model
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pymongo==4.20.002. Step 1: Write the access patterns down
List every screen or job that reads or writes data, with its lookup key, its result and a rough rate; an order of magnitude is enough.
- Rider home: one rider with up to 10 saved places, by rider ID; the most frequent read.
- Trip receipt: one trip with the driver's name and car plate, pickup, drop-off and the fare lines, by trip ID.
- Trip history: a rider's 20 most recent completed trips, newest first, by rider ID.
- Driver earnings: one driver's completed trips between two dates, by driver ID.
- Support search: a rider's completed trips above a fare amount, newest first.
Writes matter too. A trip is updated a few times until it completes, then never changes. Drivers change cars a few times a year. A rider takes a few trips a week; a full-time driver gives about 25 a day.
03. Step 2: Decide embed or reference, field by field
For each relationship, choose between embedding, which puts the related data inside the parent document, and referencing, which stores only the other document's ID. Ask four questions:
- Is it read together with the parent? Embedding answers both in one read.
- Is it bounded? An array with a known, small maximum is safe to embed. An array that grows for as long as the parent lives is not.
- Does it change on its own, or is it queried on its own? Then it usually belongs in its own collection.
- Must it stay as it was? A receipt must show the car that actually came, even after the driver changes car. That calls for an embedded copy, called a snapshot.
Applied to the list: saved places are bounded and read with the rider, so embed them. Fare lines (base, distance, time, tolls) are bounded and read with their trip, so embed them. Trips are unbounded per rider and per driver and are queried on their own, so they get their own collection and refer to the rider by rider_id. The driver is referenced by ID and snapshotted (name and plate) in the trip.
Why not embed trips in the rider, so that the history is one read? MongoDB documents must be smaller than 16 mebibytes (MiB), and the whole document is read even when the screen shows 20 trips. The bson module that ships with PyMongo encodes a document as BSON, the format to which the size limit applies:
from datetime import datetime, timezone
import bson # ships with PyMongo
trip = {
"_id": "T0000001",
"rider_id": "R0042",
"driver": {"id": "D007", "name": "Amira Khan", "plate": "LK21 XRT"},
"status": "completed",
"requested_at": datetime(2026, 10, 3, 8, 15, tzinfo=timezone.utc),
"pickup": {"address": "12 Mill Lane", "lat": 51.5101, "lon": -0.134},
"dropoff": {"address": "4 Dock Road", "lat": 51.5033, "lon": -0.0195},
"fare": {
"currency": "GBP",
"total": 18.4,
"lines": [
{"kind": "base", "amount": 3.0},
{"kind": "distance", "amount": 12.6},
{"kind": "time", "amount": 2.8},
],
},
}
LIMIT = 16 * 1024 * 1024 # 16 MiB: the maximum BSON document size
def rider_size(n: int) -> int:
rider = {"_id": "R0042", "name": "Lena Ortiz", "trips": [trip] * n}
return len(bson.encode(rider))
print(f"one trip document: {len(bson.encode(trip)):,} bytes")
for n in (20, 1_000, 10_000):
print(f"rider with {n:>6,} embedded trips: {rider_size(n):>10,} bytes")
per_trip = (rider_size(10_000) - rider_size(1_000)) / 9_000
print(f"each extra embedded trip adds {per_trip:.0f} bytes")
print(f"the 16 MiB limit is hit after about {LIMIT / per_trip:,.0f} trips")python sizes.pyone trip document: 461 bytes
rider with 20 embedded trips: 9,343 bytes
rider with 1,000 embedded trips: 465,943 bytes
rider with 10,000 embedded trips: 4,668,943 bytes
each extra embedded trip adds 467 bytes
the 16 MiB limit is hit after about 35,926 tripsAbout 36,000 trips sounds safe, but a driver document with the same array, at 25 trips a day, hits the limit in about four years. Long before that, every history screen reads the whole document, almost half a megabyte at 1,000 trips, to show 20. And every new trip rewrites a growing document. MongoDB's own guidance lists unbounded arrays as a schema anti-pattern for these reasons.
When a parent does need a few children in the same read, MongoDB suggests the subset pattern: embed a small, capped list, such as the three latest trips for the home screen, and keep the full set in its own collection. The embedded list is a copy, so the application keeps it in step: when a listed child changes, it updates both places, ideally in one transaction. Stored summaries such as an average rating work the same way; MongoDB never recomputes a field itself.
04. Step 3: Snapshot what must not change, and validate the shape
Documents in one collection can differ in shape, which makes both evolution and mistakes easy. Schema validation lets the server reject documents that break your rules. You attach a $jsonSchema validator to the collection: required fields, BSON types and allowed values. By default it applies to every insert and update and rejects a failing write with error code 121.
The script creates the trips collection with a validator, books a trip that copies the driver's current name and plate, then lets the driver change car. Finally it tries to insert a trip written by an old app version, with an unknown status and the fare total as a string:
import os
from datetime import datetime, timezone
from pymongo import MongoClient
from pymongo.errors import WriteError
db = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))["rides"]
for name in ("drivers", "trips"):
db.drop_collection(name)
TRIP_RULES = {
"bsonType": "object",
"required": ["rider_id", "driver", "status", "requested_at", "fare"],
"properties": {
"rider_id": {"bsonType": "string"},
"status": {"enum": ["requested", "accepted", "completed", "cancelled"]},
"requested_at": {"bsonType": "date"},
"driver": {"bsonType": "object", "required": ["id", "name", "plate"]},
"fare": {
"bsonType": "object",
"required": ["currency", "total"],
"properties": {"total": {"bsonType": ["double", "int", "decimal"]}},
},
},
}
db.create_collection("trips", validator={"$jsonSchema": TRIP_RULES})
db.drivers.insert_one({"_id": "D007", "name": "Amira Khan", "plate": "LK21 XRT"})
# Book a trip: copy the driver's details as they are right now (a snapshot).
d = db.drivers.find_one({"_id": "D007"})
db.trips.insert_one({
"_id": "T0000001",
"rider_id": "R0042",
"driver": {"id": d["_id"], "name": d["name"], "plate": d["plate"]},
"status": "completed",
"requested_at": datetime(2026, 10, 3, 8, 15, tzinfo=timezone.utc),
"fare": {"currency": "GBP", "total": 18.4},
})
# A month later the driver changes car.
db.drivers.update_one({"_id": "D007"}, {"$set": {"plate": "MX24 BKV"}})
print("driver now drives:", db.drivers.find_one({"_id": "D007"})["plate"])
print("old trip receipt: ", db.trips.find_one({"_id": "T0000001"})["driver"]["plate"])
# An old app version sends a status the schema does not know and a string total.
try:
db.trips.insert_one({
"_id": "T0000002",
"rider_id": "R0042",
"driver": {"id": "D007", "name": "Amira Khan", "plate": "MX24 BKV"},
"status": "done",
"requested_at": datetime(2026, 11, 2, 9, 0, tzinfo=timezone.utc),
"fare": {"currency": "GBP", "total": "18.40"},
})
except WriteError as err:
print("rejected, code", err.code)
for rule in err.details["errInfo"]["details"]["schemaRulesNotSatisfied"]:
for prop in rule.get("propertiesNotSatisfied", []):
reason = prop["details"][0]["operatorName"]
print(f" - {prop['propertyName']} failed {reason}")
print("trips stored:", db.trips.count_documents({}))python schema.pydriver now drives: MX24 BKV
old trip receipt: LK21 XRT
rejected, code 121
- status failed enum
- fare failed properties
trips stored: 1The receipt still shows LK21 XRT, the car that came, while the driver document moved on. Had the trip stored only driver_id, every old receipt would show the new plate. This is deliberate duplication: the copy is a historical fact, not a cache. Copy only what the trip needs, and keep id so the live driver is one lookup away.
The bad insert was rejected and named the failing properties: status failed its enum, and fare failed because of a rule inside its properties. Without the validator it would have been stored, and found later by whoever reads it, such as an analytics export (lesson 5).
05. Step 4: Index the main query and prove it with explain()
Load 20,000 seeded trips for 500 riders. The script reuses the validated collection, so every generated trip must pass the schema:
import os
import random
from datetime import datetime, timedelta, timezone
from pymongo import MongoClient
db = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))["rides"]
rng = random.Random(42)
START = datetime(2026, 8, 1, tzinfo=timezone.utc)
trips = []
for n in range(1, 20_001):
d = rng.randint(1, 80)
trips.append({
"_id": f"T{n:07d}",
"rider_id": f"R{rng.randint(1, 500):04d}",
"driver": {"id": f"D{d:03d}", "name": f"Driver {d}", "plate": "LK21 XRT"},
"status": "completed" if rng.random() < 0.85 else "cancelled",
"requested_at": START + timedelta(minutes=rng.randint(0, 90 * 24 * 60)),
"fare": {"currency": "GBP", "total": round(rng.uniform(6, 60), 2)},
})
db.trips.delete_many({})
db.trips.insert_many(trips)
print("trips:", db.trips.count_documents({}))
print("R0042 completed:", db.trips.count_documents({"rider_id": "R0042",
"status": "completed"}))python load.pytrips: 20000
R0042 completed: 35The trip history query has two equality conditions (rider_id, status), a sort (requested_at descending) and a limit of 20. A compound index covers several fields in a fixed order, and the order matters. MongoDB's ESR guideline says: put Equality fields first, then the Sort field, then any Range field. Equality fields first narrow the index to one contiguous run of entries; inside that run the sort field is already in order, so the server reads the first 20 entries and stops.
The script creates candidate indexes and asks the server for an explain plan with execution statistics. A plan is a chain of stages: COLLSCAN reads every document, IXSCAN walks an index, FETCH loads documents, SORT sorts in memory and LIMIT stops early. hint forces a given index, and {"$natural": 1} forces a collection scan, so you can compare plans for the same query:
import os
from pymongo import MongoClient
db = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))["rides"]
INDEXES = {
"sort_first": [("requested_at", -1), ("rider_id", 1), ("status", 1)],
"esr": [("rider_id", 1), ("status", 1), ("requested_at", -1)],
"esr_range": [("rider_id", 1), ("status", 1), ("requested_at", -1),
("fare.total", 1)],
"ers_range": [("rider_id", 1), ("status", 1), ("fare.total", 1),
("requested_at", -1)],
}
for name, keys in INDEXES.items():
db.trips.create_index(keys, name=name)
def explain(query: dict, hint) -> dict:
cmd = {"find": "trips", "filter": query, "sort": {"requested_at": -1},
"limit": 20, "hint": hint}
return db.command("explain", cmd, verbosity="executionStats")
def stages(plan: dict) -> str:
plan = plan.get("queryPlan", plan) # some plans wrap the tree in queryPlan
names = []
while plan:
names.append(plan["stage"])
plan = plan.get("inputStage")
return " > ".join(names)
def report(query: dict, hints: list) -> None:
for hint in hints:
out = explain(query, hint)
stats = out["executionStats"]
label = "collscan" if isinstance(hint, dict) else hint
print(f"{label:<11} {stages(out['queryPlanner']['winningPlan']):<23} "
f"{stats['totalKeysExamined']:>6} {stats['totalDocsExamined']:>6} "
f"{stats['nReturned']:>8}")
print(f"{'plan':<11} {'stages':<23} {'keys':>6} {'docs':>6} {'returned':>8}")
history = {"rider_id": "R0042", "status": "completed"}
report(history, [{"$natural": 1}, "sort_first", "esr"])
print("-- with a range on fare.total >= 40")
report({**history, "fare.total": {"$gte": 40}}, ["esr_range", "ers_range"])python history.pyplan stages keys docs returned
collscan SORT > COLLSCAN 0 20000 20
sort_first LIMIT > FETCH > IXSCAN 11390 11390 20
esr LIMIT > FETCH > IXSCAN 20 20 20
-- with a range on fare.total >= 40
esr_range LIMIT > FETCH > IXSCAN 36 12 12
ers_range FETCH > SORT > IXSCAN 12 12 12Read keys (index entries examined), docs (documents examined) and returned together. The collection scan read all 20,000 documents and sorted them in memory to return 20. The sort_first index leads with the sort field, so the server walks trips from newest to oldest across all riders and checks each one: 11,390 entries for 20 matches. The ESR index examined exactly 20 keys and 20 documents, with no SORT stage. When examined equals returned, the index fits the query.
The range part shows the trade-off the guideline describes. With fare.total after the sort field (esr_range), the server reads this rider's 35 completed trips in time order, skips those under 40 inside the index, and needs no sort. With the range before the sort (ers_range), it reads only the 12 matching entries but must sort them in memory. For a very selective range, ERS can win; for a broad range, the in-memory sort grows with the result.
Keep the indexes your patterns need, not every candidate. esr_range starts with the three fields of esr, so it also serves the history query; patterns 3 and 5 can share it, and the other candidates are dropped. The driver earnings pattern gets {driver.id: 1, status: 1, requested_at: -1}: equality on driver and status, then the date range on the sort field. The rider home and the receipt read by _id, which is always indexed.
06. Check your understanding
07. Apply it
Take the five access patterns of your ride-hailing project. For each relationship, write one line: embed, reference or snapshot, and why. Write a $jsonSchema validator for your trips. Index each main query, load a few thousand generated trips and keep one explain() result per query; where keys examined, documents examined and returned are far apart, change the index or the shape.
08. Review prompt
Without looking back:
- Name the four questions that decide between embedding and referencing.
- Give two reasons, other than the 16 MiB limit, not to embed an array that keeps growing.
- When is duplicating data the correct design, and what should you copy?
- State the ESR guideline, and say which explain() numbers show that an index fits a query.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.