Skip to content

    System Design

    MongoDB and Document Modelling: Embed, Reference or Subset

    Decide what to embed in a MongoDB document and what to reference, bound arrays under the 16 MiB limit, and use the subset pattern, with an in-memory model lab.

    By Published 13 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: NoSQL Types: Key-Value, Document, Wide-Column and Graph

    What you'll learn: By the end of this lesson you will be able to choose, for any one-to-many relationship, between embedding and referencing from the access pattern and not from habit, explain what the 16 MiB document limit and an unbounded array do to a design, apply the subset pattern and say what it costs, read the figures of an explain report (COLLSCAN, IXSCAN, documents and keys examined), and state what is and is not atomic. A small in-memory model lab counts each choice, and it is a model, not MongoDB.

    A filing cabinet can hold one folder per customer with everything about the customer inside: the address, the last five orders, the notes. One pull and you have the whole story. The folder fattens as years pass, and when a clerk needs every order for one product, they must open every folder. The alternative is index cards that point into other cabinets: nothing is duplicated and any cabinet can be searched on its own, but a customer's story now takes several walks.

    A document database makes that choice yours, per relationship. NoSQL types placed MongoDB in the document family and listed its structural limits; normalization and denormalization argued the same trade for tables, and SQL vs NoSQL is the choice between families. This lesson is the working method inside a document store: what goes in the folder, what goes on a card, and what to do when a folder keeps growing.

    Verified against the current MongoDB manual (the embedding page was labelled version 9.0 when read) and a model lab, on 2026-12-01. Check the pages for the version you run.

    The core idea

    Model for the questions the application asks. The manual's rule is that data accessed together should be stored together. MongoDB documents in one collection are not required to have the same fields or types, so the schema can change as access patterns change; schema validation is there when you want fixed structure. What stays your decision is, for every relationship, whether the related data lives inside the document (embedded) or in another collection (referenced).

    Embed Reference
    What it is Related data inside the parent document, in arrays and sub-documents A link (an id) from one document to another, resolved by the application or by $lookup
    Shape Denormalized: related data is retrieved in a single operation Normalized: data is split and not duplicated
    Reads One read gets everything More reads or a join
    Writes Updating related data is one atomic write on one document Related changes are separate writes
    Grows The document grows, up to a limit of 16 mebibytes Each collection grows on its own

    Three illustrations run through the lesson: a minimal example (a product with its store offers, embedded and then referenced), a realistic example (ShopStream's reviews on a product page) and a failure example (an array that grows until the document is refused).

    Reading one product page with embedded offers and with referenced offersApplication to Products (1 read); Application to Products (read product); Application to Offers (read offer)MODEL A: EMBEDMODEL B: REFERENCEApplication: model AApplicationmodel AProducts: offers insideProductsoffers insideApplication: model BApplicationmodel BProducts: name onlyProductsname onlyOffers: one per storeOffersone per store1 readread productread offer

    Figure 1. One page, two models. How to read this: in model A the application makes one read and gets every store's offer with the product. In model B it makes two reads and gets only the product and the offer for the store being viewed.

    Embedding: one read, one atomic write

    The manual describes embedded documents as storing related data in a single document, in arrays and sub-documents, so an application can retrieve related data in one database operation and update it in one atomic write. The pattern suits "contains" relationships, such as a contact and its address, and one-to-many relationships where the many are only ever viewed in the context of the one.

    The costs are the other face of the same property. Embedded data is duplicated if it also lives elsewhere. A read returns the whole document, so a rarely wanted part rides along on every read. And the document has a ceiling: documents must be smaller than 16 mebibytes, and nesting is limited to 100 levels.

    Referencing: split what changes or stands alone

    References link one document to another; the application resolves them, or $lookup and $graphLookup join collections in an aggregation. The manual lists when to consider references: embedding would duplicate data without a read benefit that outweighs it (for example when the embedded data changes often), the relationship is many-to-many or a large hierarchy, or you need to query the related entity on its own.

    erDiagram accTitle: The referenced catalogue model accDescr: A product has many offers, one per store, kept in a separate offers collection that holds the product id and the store id. A product also has many reviews, kept in a reviews collection that holds the product id and a timestamp. PRODUCT ||--o{ OFFER : "productId" PRODUCT ||--o{ REVIEW : "productId" PRODUCT { int _id string name } OFFER { string _id int productId int storeId int priceCents } REVIEW { string _id int productId int ts }

    Figure 2. The referenced model. How to read this: each line is a reference held in the many side. An offer carries its product id and store id; a review carries its product id and a timestamp.

    Illustration 1: ShopStream offers, embedded and referenced

    ShopStream sells in 5,000 stores (the course's illustrative number), each with its own price and stock for a product. The lab builds 20 products in two models: A embeds the 5,000 offers in each product document, B keeps products and offers in two collections, with an index on product id and store id. A shopper opens product 9001 at store 7.

    Expected output, captured from a real run (Java 25.0.3, 2026-12-01):

    Catalogue: 20 products, 5000 stores, one offer (price and stock) per product and store.
    Model A embeds the 5000 offers in each product document: product 9001 is 243938 bytes.
    Model B keeps products (34 bytes) and offers (100000 documents, 77 bytes each) in two collections.
    
    == 1. A shopper opens product 9001 at store 7 ==
    model          queries  documents examined  bytes returned  offer plan
    A embedded           1                   1          243938  -
    B referenced         2                   2             111  IXSCAN (1 key, 1 document)
    A is one read that carries every store's offer; B is two reads that carry only the product and one offer.

    Model A made one read and returned 243,938 bytes of JSON for one shopper's one offer. Model B made two reads and returned 111 bytes. Sizes here are compact JSON bytes, not BSON, so treat them as a ratio. The manual's own phrasing is about access patterns: the product page needs one store's offer, so the 4,999 other offers are read amplification. Whether two reads cost more than one large read depends on the server and the network, which this lab does not measure.

    Now every store changes its price for product 9001 in a promotion.

    Expected output, captured from a real run (Java 25.0.3, 2026-12-01):

    == 2. A promotion: every store changes its price for product 9001 ==
    model          write operations  distinct documents written
    A embedded                 5000                           1
    B referenced               5000                        5000
    In A all 5000 writers meet in one document (so the 'single-document writes are atomic' rule applies to all of them); in B they spread over 5000 documents. The model is single-threaded and shows no timing.

    In A, every store's price change lands on one document, so one document is the unit all those writers share. That makes updates to a store's own offer safe from partial writes, and it also means every writer competes for the same document. The model shows the count of documents, not any slowdown. The manual's referencing guidance fits: data that changes frequently is a reason to reference.

    The product page reads by product. The store app asks the other question: which products does store 7 sell? In model A the answer lives inside every product document. In B it is a query on the offers collection by store id, and it depends on an index.

    Expected output, captured from a real run (Java 25.0.3, 2026-12-01):

    == 3. Which products does store 7 sell? (query the offer on its own, in model B) ==
    plan       keys examined  documents examined  returned
    COLLSCAN               0              100000        20
    IXSCAN                20                  20        20
    The first query ran before an index on storeId existed, the second after createIndex(storeId).

    Explain results name the plan with stages. If no appropriate index exists the planner uses a COLLSCAN, where each document is compared with the query. With an index you see IXSCAN. totalDocsExamined counts documents examined, not returned, and totalKeysExamined counts index entries. The model reports the same three figures. A COLLSCAN examining 100,000 documents to return 20 is the signature of a missing index. Indexes are not free either: a collection can have at most 64. Query plans and B-tree indexes cover reading plans in depth, in a SQL setting.

    Illustration 3: the array that never stops growing

    Reviews seem a natural thing to embed: the page shows them. The manual calls an array with no limit on its elements an anti-pattern: the document might exceed the 16 MB limit, and an unbounded array can strain application resources and decrease index performance. The fix it names is bounding arrays with subsetting and referencing.

    Expected output, captured from a real run (Java 25.0.3, 2026-12-01):

    == 4. Reviews embedded in the product document with no bound ==
    one review is about 65 bytes of JSON; the push number 237864 was refused
    237863 reviews fit; the document was 16777209 bytes (the limit is 16777216)
    Long before the limit, every read of the product carries every review.

    The push that would have reached the limit was refused. The refused write is the loud failure; the quiet one comes much earlier, when every read of a popular product drags every review along. The lab's size check is a few lines:

    List<Object> array = listOf(stored.doc.get(field));
    long added = Json.bytes(element) + (array.isEmpty() ? 0 : 1);
    if (stored.size + added >= MAX_DOCUMENT_BYTES) {
        throw new DocumentTooLargeException(stored.size + added);
    }
    array.add(element);
    stored.size += added;

    The count of 237,863 is for 65-byte JSON reviews against a JSON-byte limit, not BSON; it is an illustration of the shape of the failure, not a number to plan with.

    The subset pattern: embed what the page needs, reference the rest

    The manual's example is the one ShopStream has: the product page shows the newest few reviews, and older ones are read less often. The subset pattern embeds a few reviews in the product document and keeps all of them in a separate reviews collection. The manual states the cost plainly: this approach duplicates data, which makes updates expensive, so it is best when the embedded part is not updated often. The alternative, pure referencing, solves the unbounded array but adds latency because the application queries the reviews collection.

    The lab builds one product with 5,000 reviews in three designs and reads the page, which needs the 3 newest.

    Expected output, captured from a real run (Java 25.0.3, 2026-12-01):

    == 5. The product page needs the 3 newest of 5000 reviews ==
    design                            queries  documents examined  bytes returned
    all reviews embedded                     1                   1          343934
    reviews in their own collection          2                   4             317
    subset: newest 3 embedded + all          1                   1             254
    The newest-3 query used IXSCAN, reading 3 keys, not 5000.
    
    A new review arrives (ts 5001), then another (ts 5002) during which the process dies:
    review 5001: 2 writes (insert into reviews, replace the embedded subset)
    review 5002: inserted, crash before the subset write
    the product page shows newest ts 5001; the reviews collection holds newest ts 5002
    Two writes are two operations: nothing in this model makes them one. A repair job rebuilds the subset.
    after the repair the page shows newest ts 5002

    The subset design returned 254 bytes in one read, the referenced design 317 bytes in two reads (an index on product id and timestamp let the "newest 3" query read 3 keys), and the all-embedded design 343,934 bytes. The price of the subset shows in the second half: a new review is two writes, and the crash between them left the page one review behind.

    sequenceDiagram accTitle: A subset write that crashes between its two writes accDescr: A new review is inserted into the reviews collection, which succeeds. The process then dies before it updates the embedded subset in the product document. The product page keeps showing the older reviews until a repair job rebuilds the subset from the reviews collection. participant S as Review service participant R as reviews collection participant P as product document S->>R: insert review 5002 R-->>S: ok Note over S,P: process dies here S--xP: replace latestReviews (never sent) Note over P: page still shows 5001 S->>R: repair job: read newest 3 S->>P: replace latestReviews

    Figure 3. The two writes of the subset pattern. How to read this: the first write is durable on its own. The second never happens, so the subset is stale until something rebuilds it.

    What is atomic

    MongoDB's write operations are atomic at the single-document level, even when they modify several values inside one document. When one write operation such as updateMany modifies many documents, each document's change is atomic but the operation as a whole is not, and other operations may interleave. Distributed transactions exist for several-document atomicity, but the manual says a transaction usually costs more than single-document writes and is not a replacement for effective schema design. This is the quiet benefit of embedding: what must change together can live in one document. It is also why the subset pattern needs a repair path, since its two writes are two operations. The manual's pattern for concurrent updates is to put the expected current value in the filter so a conflicting update matches nothing.

    Build it: the in-memory model lab

    Setup. From examples/backend (no Docker, no MongoDB server):

    ./gradlew :labs:mongodb-document-model:test
    ./gradlew -q :labs:mongodb-document-model:run

    The command runs 13 tests; the second prints the report quoted above, which is examples/golden/mongodb-document-model.txt. The code is in examples/backend/labs/mongodb-document-model/src/main/java/buildingai/labs/documentmodel/.

    What it is, and is not. DocStore is a stand-in written from the manual: single-threaded, in memory, collections of JSON-like documents, a size counted as compact JSON bytes, a fixed rule for using an index, and per-query counters of keys examined, documents examined and bytes returned. It is not MongoDB: no server, no BSON, no query planner, no projections, no transactions, no concurrency or replication, and no timings. Every figure above is the model's own count.

    Break it. In DocStore.Collection.pick, make the method always return null: the index tests fail and the Demo reports COLLSCAN everywhere. Restore it and run the tests again.

    Stretch. Add the bucket pattern (one document per product per day of reviews) and compare its documents examined with the subset design.

    Choosing: embed, reference or subset

    flowchart TD accTitle: Choosing between embedding, referencing and the subset pattern accDescr: A decision tree. If the related data is read with the parent and is small and bounded, embed it. If it is large, grows without bound, changes often or is queried on its own, reference it. If the parent page needs only a few of a large set, embed that subset and reference the full set. Q1{"Read together with the parent, small and bounded?"} Q1 -- "Yes" --> E["Embed"] Q1 -- "No" --> Q2{"Does the parent page need a few of them?"} Q2 -- "Yes, and they rarely change" --> S["Subset: embed a few, reference all"] Q2 -- "No: large, growing, changing or queried alone" --> R["Reference, with an index on the link"]

    Figure 4. A decision tree per relationship. How to read this: answer for each relationship separately; one product document can embed its attributes, reference its offers and use a subset for reviews.

    Choice Gain Cost Wrong when
    Embed One read; one atomic write Document growth; duplicated data; whole-document reads The array is unbounded or the part is queried alone
    Reference No duplication; query each side alone More reads or a join; needs an index on the link The parent is always read with all of its children
    Subset Small read for the common case; bounded document Duplicated data; two writes that need a repair path The subset changes on most writes

    The other side of this topic

    A front end that renders a product page pays for the document it is sent. A large embedded array becomes a large response unless the server trims it; the front-end lessons on API integration and HTTP semantics (plain text until published) cover that side. Modelling the server's documents to match the page is the same decision seen from the other end.

    In practice: ShopStream's catalogue offers and reviews

    This is an educational scenario on the course's running example ShopStream. Numbers are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    The catalogue holds 100,000 products per region and 5,000 stores. Each store sets its own price and stock per product, owners change prices through the day, and popular products collect thousands of reviews. The product page shows the product, the shopper's store's offer and the newest three reviews. The ShopStream data model already places the catalogue in a document store.

    Starting architecture

    A first version embeds both offers and reviews in the product document, so one read serves the page.

    Options considered

    Option Behaviour Risk
    A. Embed offers and reviews One read Documents grow with stores and reviews; every read is large; all stores' price edits hit one document
    B. Reference offers and reviews Small documents; offers queried by store Two or three reads per page
    C. Reference offers, subset for reviews One product read plus one offer read A repair path for the subset

    The decision

    Option C. Offers are referenced: a collection with a compound index on product id and store id for the page and a separate index on store id for the store app. Reviews use the subset pattern: three embedded, all in a reviews collection with an index on product id and time. The product document keeps its attributes embedded, since they are read together and small and bounded.

    Rollout and verification

    Build the new collections beside the old, switch reads for a few products, and compare the explain figures with the lab's shape: the offer read should be an index scan examining one key and one document, and the newest-reviews read should examine as many keys as it returns. Verification is "no COLLSCAN on the page's queries and the subset's newest timestamp equals the reviews collection's newest".

    The 2 a.m. failure

    Customers report new reviews missing from a product page. The review insert succeeded and the service crashed before updating the product's subset, which is the two-write gap in the lab. The check is to compare the subset's newest timestamp with the newest review for the product. The mitigation is to rebuild the subset for that product. The lasting fix is a job that rebuilds a product's subset from the reviews collection on a schedule and after any crash, because the pattern's two writes are not one atomic step.

    Architect's notes

    • Start from the page or the query. Write the reads that must be one round trip, then embed what they need.
    • Bound every array. Ask what its size is in a year, and use subsetting or references if you cannot say.
    • Index the link of every reference, and read plans for COLLSCAN.
    • Count the writes. If two documents must change together, you need a repair path or a transaction, and the manual says a transaction is no substitute for good schema design.

    Common mistakes

    • Embedding by habit. "Documents mean embed" ignores unbounded growth and whole-document reads.
    • Referencing without an index. The second query becomes a collection scan.
    • Assuming a multi-document update is atomic. Each document is; the operation is not.

    Key takeaways

    • Data accessed together should be stored together; decide per relationship.
    • Embedding gives one read and one atomic write, and costs growth and duplication.
    • An unbounded array fails at 16 MiB and hurts long before.
    • The subset pattern keeps the page's few items inside the document and the full set outside, at the cost of two writes.
    • Write atomicity is per document; plan a repair path for patterns that need two.
    • The lab's counts come from a model: 243,938 bytes against 111 for one offer, 100,000 documents examined without an index against 20 with one.

    Practice exercises

    Exercise 1 (20 min). For a user, their addresses, their orders and their login events, say what you would embed and what reference, and why.

    Exercise 2 (1 hour). Run the lab and explain, from section 2, which model concentrates the promotion's writes in one document.

    Exercise 3 (2 hours). Run "Break it", then add a bucket pattern for reviews and compare documents examined for the newest-three query.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments