Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 70 ยท Schema design

Embedding vs Referencing

Decide when to embed related data in one MongoDB document and when to reference it from another collection, using access patterns, atomicity and size limits.

The most important design decision in MongoDB is a small one that you make over and over: when two pieces of data are related, do you embed one inside the other, or do you keep them in separate documents and reference one from the other? An order with its line items can be one document or two collections. A blog post with its comments can be one document or two. There is no universal answer, but there is a good method for finding the right one.

This lesson gives you that method. The short version: design for how your application reads and writes the data, not for how the data looks on a whiteboard. You will see the two layouts side by side, the sizes of relationship that push you one way or the other, and three runnable stand-ins that show duplication, atomicity and a simple decision checklist in code.

The mongosh snippets are real MongoDB syntax, shown read-only. The TryIts run on plain JavaScript arrays and objects, so they demonstrate the design consequences (how many documents change, what stays consistent), not database speed.

How many on the other side?

One to one A user and their profile settings.
One to few A person and their addresses.
One to many A product and its reviews.
One to squillions A server and its log lines.

The bigger the many, the more you reference.

1 / 3

The same data, two layouts

Here is one order that embeds its customer snapshot and line items:

JavaScript
{
  _id: 1001,
  placed: ISODate("2026-03-01"),
  customer: { _id: 7, name: "Mia", city: "Oslo" },
  items: [
    { sku: "A1", name: "Trail Shoe", price: 89, qty: 1 },
    { sku: "B2", name: "Water Bottle", price: 14, qty: 2 }
  ],
  total: 117
}

And the same order with references, where the customer and the products live in their own collections:

JavaScript
// orders
{ _id: 1001, placed: ISODate("2026-03-01"), customerId: 7,
  items: [ { productId: "A1", qty: 1 }, { productId: "B2", qty: 2 } ] }

// customers
{ _id: 7, name: "Mia", city: "Oslo" }

// products
{ _id: "A1", name: "Trail Shoe", price: 89 }

The embedded order is read with a single findOne. The referenced order needs three lookups, either from your application code or with $lookup in an aggregation (Joining with $lookup). In return, a product's price lives in exactly one place.

Notice that the "embedded" order above still copies the product's name and price into the line items. That is deliberate and often correct: an order must record the price at the time of purchase, so it should not follow later price changes. Copying data is not always duplication to avoid; sometimes it is a historical record.

Relationship sizes

Thinking in sizes helps you choose quickly.

One to one. A user and their settings. Embed, unless the settings are large and rarely needed, in which case a separate document keeps the user document light.

One to few. A person with two or three addresses, a recipe with a dozen steps. Embed as an array. The count is small and bounded, and you almost always want them together.

One to many. A product with a few hundred reviews, a customer with a few hundred orders. This is the judgement zone. If you usually show the children together with the parent and the number is capped, embed. If children are queried on their own, grow steadily or are edited independently, give them their own collection and store the parent's _id in each child (productId in each review).

One to squillions. Billions of log lines, sensor readings or events for one source. Never embed them: store each in its own collection with a reference to the source, and often group them into buckets (Schema Design Patterns). Putting the reference on the "many" side avoids an array that can never stop growing.

Let access patterns decide

List the screens and operations of your application, and for each, write down what is read and written together. Then model so that the common operations touch few documents:

  • A product page shows the product, its specs and the five latest reviews. Embed specs, embed a handful of reviews, keep the full review history in a reviews collection.
  • An admin screen shows all reviews by one user across products. That is a query on reviews alone, so reviews need to be their own collection anyway.
  • Orders are read when a customer opens "my orders", and each order is written as a whole. Embed the line items.

Workload, not elegance, is the criterion: a design that makes the hot path a single read is better than one that is theoretically tidy.

Atomicity: one document is one unit

A write to a single document is atomic: other readers see the whole change or none of it, even when it touches many fields and array elements. Writes across two documents are not atomic unless you use a multi-document transaction (Multi-Document Transactions), which costs more.

If two pieces of data must always change together (an order's line items and its total, for example), embedding them is the simplest way to keep them consistent. The first stand-in shows the difference when something fails halfway through.

JS One write or two? Consistency when something fails

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After the crash the embedded order is exactly as before, while the referenced layout now has an item that the stored total does not include. That is the kind of half-written state transactions exist to prevent. It is not that referencing is wrong; it means that references across documents need extra care.

Duplication and staleness

The price of embedding data that is shared is duplication. If Mia's name is copied into every order, renaming her touches every order, and any copy you forget to update goes stale. Referencing keeps one authoritative copy but adds a lookup on every read.

The second stand-in counts how many documents change when a customer is renamed under each design.

JS Renaming a customer under two designs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Customers rarely rename themselves, and an order is arguably a snapshot anyway, so embedding the name may be perfectly fine. A product's current price that appears in thousands of catalogue listings, and changes weekly, is a better candidate for referencing. When you do want a copy plus a pointer, store a small snapshot (name, maybe city) and the _id: that is the extended reference pattern, covered next lesson.

Document growth and the 16 MB limit

A document cannot exceed 16 MB. That is a lot of room, but an array that gains an element on every event can reach it eventually, and long before that you pay for loading and rewriting large documents on every small update. Ask of every embedded array: "What is the maximum length, and what happens at that maximum?" If the honest answer is "no limit", the children need their own collection. See Common Performance Pitfalls.

A decision checklist

The third stand-in turns the questions into a function. It is a rule of thumb to practise the reasoning, not a replacement for thinking about your own workload.

JS A rule-of-thumb decision helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real decisions mix these signals, and most good schemas use both techniques: embed what is read and written together, reference what is large, shared or independent, and copy a few fields where a read would otherwise need a join.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should drive the choice between embedding and referencing?

    Design for the common reads and writes: data used together is usually embedded, data that is large, shared or independent is referenced.
  2. 2. A server produces millions of log lines. How should they relate to the server document?

    An unbounded array would hit the 16 MB document limit and slow every update. Put the reference on the many side instead.
  3. 3. Why does embedding help keep an order and its line items consistent?

    Single-document writes are atomic. Changes spread over several documents need a multi-document transaction to be all-or-nothing.
  4. 4. What is the main cost of embedding data that many documents share?

    Each parent holds its own copy, so a change fans out. Copies of historical values (like the price at purchase time) are the exception: they should not change.

Summary

  • Embed data that is read together, written together and bounded; reference data that is unbounded, shared, independent or frequently edited.
  • Think in relationship sizes: one-to-one and one-to-few embed; one-to-many is a judgement call; one-to-squillions always references, with the reference on the many side.
  • Access patterns decide: make the common operations touch few documents.
  • A single-document write is atomic; spreading data over documents means extra care or a transaction.
  • Embedding shared data duplicates it and risks stale copies, except where a copy is meant to be a historical snapshot.
  • Keep every embedded array bounded, mindful of the 16 MB limit.

Next, learn the named solutions for common cases in Schema Design Patterns.