Document modelling

Embedding versus referencing, the 16 MB limit, unbounded arrays, and schema versioning inside a document.

11 min read🍃 MongoDB

A relational schema is designed around the data's structure and normalised so that every fact lives once; the queries come afterwards and joins assemble what they need. A document model is designed the other way round: start from the reads and writes the application actually makes, and shape each document so that the common ones touch one document. That is the whole skill, and every rule below — embed or reference, the 16 MB limit, the array that must not grow, the version field — follows from it.

Access patterns first

Before a single field, list the operations with their frequency: "show an order with its lines and the customer's name" (every page view), "list a customer's orders, newest first" (every visit), "update a line's quantity" (rare), "find every order containing a SKU" (a report, weekly). A document store rewards the design in which the frequent read is findOne on one document and the frequent write is updateOne on one document, and it punishes the design that needs three collections joined for the page everyone loads. The relational instinct — one table per noun — produces the second design; the document instinct produces a document per thing the application handles as a unit.

an order, as the order page reads itplaintext
{
  _id: ObjectId("..."),
  orderNumber: "ORD-2026-000412",
  customer: { id: ObjectId("..."), name: "Ada L." },     // embedded copy of what the page shows
  status: "PAID",
  placedAt: ISODate("2026-09-18T02:10:00Z"),
  lines: [ { sku: "A-1", name: "Cable", qty: 2, unitPaise: 19900 } ],
  totalPaise: 39800,
  schemaVersion: 2
}

One read for the page, one write to place it. The customer's name is copied, not joined — a deliberate denormalisation, and the honest question about every copy is what happens when the source changes. For an order, the name at the time of the order is arguably the correct value anyway; for a product catalogue embedded in ten thousand orders, a rename is ten thousand updates, and a reference is the right call.

Embed or reference

The decision, per relationship, with the questions that decide it:

Embed whenReference when
the child is read with the parent almost every timethe child is read on its own, or from several parents
the child does not exist without the parent (order lines)the child has its own lifecycle (a customer, a product)
the number of children is bounded and small (tens)the number is unbounded or large (events, comments, log entries)
the child rarely changes, or changing it with the parent is finethe child changes independently and the copies would drift

A reference is a stored _id and a second query (or a $lookup in an aggregation, which the next lesson covers and which is a join with a join's cost). The pattern that covers most real cases is both: embed the few fields the common read needs (customer.name) and reference the rest (customer.id), accepting the copy and its update cost for exactly those fields. Spring Data MongoDB maps an embedded object as a nested class and a reference with @DocumentReference (or the older @DBRef), and the second one fetches lazily or eagerly per your annotation — the JPA course's lazy-loading traps, back in a different costume.

The 16 MB limit and the unbounded array

A document may not exceed 16 MB, and long before that limit it becomes slow: every read returns the whole document, every update rewrites it, and an array that MongoDB must scan to append to costs more with each element. So the design rule is that no array may grow without bound. Order lines are bounded by how many things a person buys; a customer's orders array is not, an account's transactions array is not, a device's readings array is not. For those, the child is its own collection with a reference to the parent ({ accountId, amount, at }, indexed on (accountId, at)), or, for time series, the bucket pattern: one document per parent per hour or per day, holding that period's readings, which bounds the array by time and keeps a day's read to one document.

The tells in an existing schema: $push without $slice, an array field the application only ever appends to, a document whose size grows with the age of the account. Each one is a document that will hit the limit or the performance cliff on the customer with the most history, which is the customer you least want to lose.

Schema versioning inside the document

There is no ALTER TABLE, so a schema change is the application handling two shapes at once. The pattern is a schemaVersion field on every document and a reader that upgrades on the way in:

java
Order read(Document doc) {
    int v = doc.getInteger("schemaVersion", 1);
    if (v < 2) doc = splitCustomerNameIntoParts(doc);       // the v1 → v2 change, applied in memory
    return map(doc);
}

Write new documents at the current version, read old ones through the upgrade, and migrate the stored documents lazily (write them back at the new version when they are next saved) or in a background job over the collection in batches. That is the SQL course's expand-contract with the migration inside the application, and the discipline is the same: never make the reader depend on every document having been upgraded, and remove the upgrade code only when a query for schemaVersion: { $lt: 2 } returns nothing. MongoDB's JSON Schema validation (validator on the collection) can enforce the current shape on writes, which is the part of a relational schema worth keeping.

Spring Data MongoDB mapping, and what it hides

@Document(collection = "orders") on a class, @Id on a String or ObjectId, nested classes for embedded objects, MongoRepository<Order, String> with derived queries — the shape is Spring Data JPA's, and that is the trap: it is easy to write a relational design in annotations. Three things to keep in view. The mapped class is the schema, so a renamed field is a document the application can no longer read until the version pattern above handles it. @DocumentReference does the second query for you, and a list of references is the N+1 problem with no JOIN FETCH to reach for. And MongoTemplate with Update objects ($set, $inc, $push) updates the fields you name, where repository.save(order) replaces the whole document — the difference between a 40-byte write and a 40-kilobyte one, and between two concurrent updates to different fields both landing and the second one erasing the first.

Under the hood: what growing a document actually costs the storage engine

The 16 MB figure is a hard ceiling the driver enforces before a document ever reaches the server, but the performance cliff arrives long before that ceiling, and it is worth knowing why. BSON — the binary format every document is stored and sent as — encodes every field with a length prefix: a string carries its byte length before its bytes, a document carries its total byte length before its fields, and an array is, underneath, an ordinary BSON document whose keys are the strings "0", "1", "2" and so on rather than names you chose. That means an array is not a special, cheaper structure than an embedded object — appending an element re-encodes the array's own length prefix and, in WiredTiger (the default storage engine), can force the containing document to be rewritten if it no longer fits where it was stored. WiredTiger keeps collections as B-trees of documents; a document that grows past the space it was allocated does not grow in place, it is written to a new location and the old slot is reclaimed later, which is strictly more work than an update that keeps a document's size the same. This is the concrete mechanism behind "an array that grows without bound gets slower with every element": each append is not O(1), because each append is, at some frequency, a full document relocation.

The same fact explains why the field-update operators ($set, $inc, $push) exist as a distinct API from save()'s whole-document replace. An update that changes one field in place, without changing the document's total size, can be applied to the stored bytes without a move; an update that grows the document (a $push onto an array, a new field) cannot make that guarantee. Neither can be seen from the query document alone — db.orders.updateOne({_id}, {$push: {lines: newLine}}) looks identical in cost to $set: {status: "SHIPPED"} from the application code, but one of them is a size-changing write and the other is not.

$jsonSchema validation (the validator option on a collection, with validationLevel: "moderate" to exempt existing documents and validationAction: "warn" to log rather than reject) is MongoDB's answer to enforcing the current shape without an ALTER TABLE — it runs the schema check against every insert and update on the server, independent of whatever version-handling code the application has, which is the honest backstop for the "we upgraded the reader but forgot to write schemaVersion: 2" bug.

Try it yourself

Reason through the cost of two write patterns

Two services both store a Cart document with a items array. Service A appends a new line with $push: {items: newLine} every time a shopper adds something, and the array is capped at 50 items by the UI. Service B stores an activityLog array on the same document that records every page view during checkout, uncapped, and appends with the same $push.

Why one of these is fine and the other is a design bug, even though both use the same operator

The operator is not what decides the cost — the bound on the array is. Service A's items array is capped at 50 by the application, so its worst-case size is fixed and small: the document eventually stops growing past a known ceiling, and even the WiredTiger relocations described above happen a bounded number of times over the cart's life. Service B's activityLog has no such bound — a shopper who reloads a page forty times, or a bot crawling checkout, grows the array without limit, and the same Cart document now carries an ever-larger array that gets more expensive to append to and to read with every checkout session. The fix is not a different operator; it is the document-modelling call from earlier in this lesson — activityLog does not belong embedded in Cart at all, since it is unbounded and not read with the cart on the common path. It belongs in its own collection, keyed by cartId, or is not stored in MongoDB at all if it is just an analytics event.

Misconceptions

  • "An embedded array is a cheap way to add data to a document." BSON encodes an array as a document keyed by index, so appending to it re-encodes the array's length prefix and, once the document no longer fits its allocated storage slot, forces WiredTiger to relocate the whole document. The array is not a free-standing structure; it is part of the document's total size and total rewrite cost.
  • "schemaVersion is enough on its own to keep old and new shapes from mixing." The field only works if every write path sets it and every read path checks it; a bulk import or an admin script that writes documents directly skips both. $jsonSchema validation on the collection is the server-side backstop that catches a write the application code did not upgrade, independent of whether the reader remembered to check the version.

Sources

  • MongoDB Manual, "BSON Types" and "Document Structure" (field encoding, the array-as-keyed-document representation, the 16 MB document size limit).
  • MongoDB Manual, "Schema Validation" ($jsonSchema, validationLevel, validationAction).
  • MongoDB Manual, "Data Modeling — Building With Patterns" (the Bucket Pattern, embedding vs. referencing).
  • WiredTiger documentation, "Storage Engine" overview (B-tree page layout and document relocation on growth).
Progress is saved on this device and to your account when signed in.