Lesson 2 of 9 · 22m
Embedding, Referencing, and Bucketing
The three structural moves in document design, the growth patterns they tolerate, and why unbounded arrays are production incidents waiting patiently.
The canonical MongoDB question — embed or reference? — is incomplete. There are three useful shapes: embed for bounded composition, reference for independent lifetimes, and bucket for high-volume append-mostly data. Choosing between them is mostly a question of cardinality and write contention.
Embed bounded composition
Order line items are the classic embed:
{
_id: ObjectId(),
orderNumber: "SO-10482",
status: "paid",
items: [
{ sku: "KB-TKL", qty: 1, unitPrice: 12900 },
{ sku: "CABLE-C-2M", qty: 2, unitPrice: 1900 }
],
totals: { subtotal: 16700, tax: 1336, total: 18036 }
}The items belong to the order, appear on the same screens, and are small in number. One read gets the business object. One atomic document update can enforce item and total consistency.
Reference independent lifetimes
Comments on a post should not live in the post document. They are unbounded, often queried separately, and written by different actors. Store them in their own collection with a parent key:
{ _id: ObjectId(), postId: ObjectId("665f0a9381c4b7c8e89a24aa"), authorId: ObjectId("665f0a9381c4b7c8e89a2410"), body: "This finally explained write concern for me.", createdAt: ISODate("2026-11-29T21:04:12Z") }Yes, that means an application-side join. That is not a failure. It is a deliberate trade: comments can grow forever without making posts huge or hot.
Bucket append-mostly detail
For measurements, events, or market ticks, neither one-document-per-event nor giant arrays is ideal. Bucketing groups a time window or fixed count into one document:
{
sensorId: "boiler-17",
bucket: ISODate("2026-11-29T22:00:00Z"),
count: 2,
min: { tempC: 72.1 },
max: { tempC: 72.4 },
readings: [
{ t: 0, tempC: 72.1 },
{ t: 60, tempC: 72.4 }
]
}This gives bounded document growth and far fewer documents than raw event-per-row storage. MongoDB time series collections implement a similar idea internally and are often the better default for pure telemetry.
Field notes
- Unbounded arrays fail slowly: first larger documents, then slower updates, then migration pain.
- Do not store foreign-key style arrays with thousands of IDs inside a parent. Reverse the reference: put the parent key on each child.
- Denormalize immutable facts freely; denormalize mutable facts only with a clear repair path.
- MongoDB does not enforce references. Your application owns referential integrity, orphaned-data cleanup, and the operational consequences.
Was this lesson helpful?