Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

When would you embed related data in a MongoDB document and when would you reference other documents? Use orders, customers and products as examples.

We embed data that is owned by the parent and read with it, such as the lines of an order. We reference data that is shared by many documents, large, or updated on its own schedule, such as customers and products. When history matters, we also copy a small snapshot, such as the product name and the price at the time of purchase, into each line, and we keep an eye on the 16 MB document limit and on arrays that can grow without bound.

Why this question is asked

Modelling is where most MongoDB projects succeed or fail. A relational schema can be normalised and fixed later with joins; a document model decides up front which data travels together, and changing that later means rewriting documents. Interviewers ask this design question to see whether we choose by access pattern and ownership rather than by habit. In this answer, we will recap what embedding and referencing mean, work through orders, customers and products one by one, look at the snapshot technique for history, cover size limits, and compare @DBRef with manual references in Spring Data MongoDB.

1A Quick Recap: Embedding and Referencing

Embedding means storing related data inside the parent document as a nested object or an array. Reading the parent returns the embedded data in the same read, and a write to the whole document is atomic. Referencing means storing only the id of another document, much like a foreign key, and loading that document with a second query when we need it.

The useful way to decide is to ask three questions about each relationship. Is the related data owned by the parent, meaning it is created and deleted with it? Is it read every time the parent is read? And is it updated together with the parent, or on its own? Yes, yes and together point to embedding. Shared, rarely needed or independently updated point to referencing.

Deciding per relationship
RelationshipOwned by order?Updated with order?Choice
Order -> linesyesyesembed
Order -> customerno, shared by many ordersno, profile changes alonereference by id
Order -> productno, shared catalogueno, price changes alonereference plus snapshot

2Orders and Their Lines: Embed

Order lines are the clearest case for embedding. A line has no meaning without its order, it is created with the order, every screen that shows an order shows its lines, and the order total depends on them. Embedding gives one read for the order page and one atomic write when the order is placed.

The array is also naturally bounded. A shopping order has a handful of lines, rarely hundreds. That matters, because the size of a document affects every read and write of it.

3Customers: Reference

A customer places many orders, and the customer's profile, such as name, email or loyalty status, changes on its own schedule. If we embedded the full customer in every order, a change of email address would mean updating thousands of order documents, and some of them would inevitably be missed. So the order stores customerId, and the customer lives in its own collection.

There is an exception worth naming: the shipping address. The order should keep the address it was shipped to, even if the customer later moves. That is not the customer's current address but a fact about this order, so we embed a copy of it.

4Products: Reference, Plus a Snapshot for History

Products are shared by every order that contains them, and their price and description change often. So the line references the product by productId. But an order is a historical record: an invoice from March must show the March price, not today's. If the line held only the product id, we would show the wrong price as soon as the catalogue changed.

So we denormalise, which means deliberately copying data, a small snapshot of the fields that must be preserved into the line.

Java
// orders collection
{ _id: "o-1001", customerId: "c-42", createdAt: ISODate("2026-03-14T10:00:00Z"),
shippingAddress: { street: "Main St 1", city: "Leeds" }, // copy: fact about this order
lines: [
{ productId: "p-7", name: "Desk Lamp", unitPrice: Decimal128("19.90"), qty: 2 } // snapshot
] }
// products collection: the current truth
{ _id: "p-7", name: "Desk Lamp Pro", price: Decimal128("24.90"), stock: 130 }
// the March order still shows Desk Lamp at 19.90; the catalogue shows the new name and price

Notice that the snapshot is not a cache that must be kept in sync. It is supposed to differ from the product later, because it records what was true when the order was placed. Data copied for convenience, by contrast, does need a plan for updates, and that is where denormalisation gets expensive.

5Watch the Size Limit and Unbounded Arrays

MongoDB limits a document to 16 MB. That sounds large, but the real problem appears long before the limit: a growing document makes every read heavier, every update rewrite more data, and indexes on array fields grow one entry per element. The pattern to avoid is an unbounded array, one with no natural maximum, such as embedding every order inside the customer document. A customer who orders weekly for ten years ends up with 520 orders and a document that is read in full whenever we only want their email.

So the rule is to embed one-to-few relationships and reference one-to-many or one-to-squillions. If a parent needs a quick view of the latest children, we can embed a bounded subset, for example the last five orders, using $push with $slice to keep only five.

6@DBRef Versus Manual References in Spring Data MongoDB

Spring Data MongoDB offers @DBRef, which stores a reference in a standard format with the collection name and id, and loads the referenced document automatically when the parent is read. That convenience has a cost: one extra query per referenced document, run silently, which can become an N+1 problem when we load a list of 100 orders and each pulls its customer. With lazy = true the load is deferred through a proxy, which helps only if we rarely touch the field.

Java
// convenient but hidden queries
@DBRef(lazy = true) private Customer customer;
// explicit: store the id, load when needed, in bulk
private String customerId;
List<Order> orders = orderRepo.findByCreatedAtAfter(since); // 1 query
Set<String> ids = orders.stream().map(Order::getCustomerId).collect(toSet());
Map<String, Customer> customers = customerRepo.findAllById(ids).stream()
.collect(toMap(Customer::getId, c -> c)); // 1 more query, not 100

Manual references are often clearer: the id is a plain field, queries are explicit, and we can load related documents in one batch. Newer Spring Data MongoDB versions also offer @DocumentReference, a lighter mapping that stores just the id and can be resolved lazily; check your version. When a screen truly needs joined data, an aggregation with $lookup does the join on the server in one round trip.

7Follow-up questions

What if we need to show the customer's name on every order list?

We can embed a small snapshot, such as the customer's display name, in the order and accept that it reflects the name at order time, or resolve names in one batch query as shown. If the name must always be current, the batch lookup or a $lookup aggregation is the honest choice.

How do you update copied data when it must stay current?

With an updateMany on all documents that hold the copy, run when the source changes, often triggered by an event. It works, but it is eventually consistent and can touch many documents, which is why we copy only fields that rarely change or that are snapshots by design.

Is embedding always faster?

For reading the parent with its children, yes, one read replaces several. For queries that look for the children across all parents, such as all lines for product p-7, embedding is less convenient: we need a multikey index on lines.productId and get whole orders back. Access patterns decide.

8Conclusion

In this answer, we decided each relationship by ownership, reading pattern and update pattern. Order lines are owned and read with the order, so we embed them. Customers and products are shared and change on their own, so we reference them by id, while copying a snapshot of the product name and price, and the shipping address, because the order is a historical record. We avoid unbounded arrays well before the 16 MB limit, and we prefer explicit references loaded in batches over @DBRef, whose hidden extra queries can turn into an N+1 problem.

What to say in the interviewAbout 90 seconds aloud

Open with

I decide per relationship, by asking whether the data is owned by the parent, whether it is read with it, and whether it changes with it. Order lines are owned by the order, always shown with it, and written with it, so I embed them: one read for the order page and an atomic write when the order is placed, and the array is naturally small.

Then, if they want more

Customers are the opposite. One customer has many orders and their profile changes on its own, so I store customerId in the order and keep customers in their own collection, otherwise an email change means rewriting thousands of orders.

Products are referenced too, by productId, but because an order is a historical record, I copy a snapshot of the product name and the unit price into each line. That copy is meant to differ later; the March invoice must keep the March price. Same for the shipping address.

I keep the 16 MB limit in mind, but the real rule is no unbounded arrays, so I would never embed all orders into the customer; at most the last few with push and slice. For loading references in Spring Data, I usually avoid @DBRef because it runs a hidden query per reference, which becomes N+1 on lists.

I store plain ids and load related documents in one findAllById, or use a $lookup aggregation.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Data reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "When would you embed related data in a MongoDB document and when would you reference...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/d3f1a69e14/