Data Modeling
Embedding vs Referencing
The central modelling decision. Neither is always right; the access pattern decides.
Embed copies the related data into the parent document. Reference stores an id and fetches (or $lookups) the rest. The question is not 'which is MongoDB-like'. It is: is this read together, owned by the parent, and bounded?
Embed
- One round trip
- One-document atomic update
- Duplication if many parents share it
- Document grows with the child list
Reference
- Independent lifecycle and queries
- No 16MB surprise from this list
- Extra read or $lookup
- Two-document writes need care (transactions later)
// Embed — line items are the order. Bounded. Never shared.
{
userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"),
amount: 4900,
items: [
{ name: "Mechanical Keyboard", quantity: 1, unitPrice: 4500 },
{ name: "USB-C Cable", quantity: 2, unitPrice: 200 }
]
}
// Reference — orders are not the user. Unbounded. Listed on their own.
{ name: "Rahul", city: "Bangalore" }
{ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"), amount: 4900 }Embed when: 1:1 or 1:few, always fetched with the parent, not reused as a first-class page. Reference when: the child has its own queries (Rahul's order history), many parents would copy a large mutable object, or the array has no natural cap. Hybrid is normal: items embed a snapshot of name and unitPrice, and may still hold productId if you need to join the catalogue later.
Interview question
How do you decide between embedding and referencing?
Embed when the data is read together, owned by the parent, and bounded in size. Reference when it is large, shared between parents, or grows without limit. Order line items embed. A user's orders reference. Access pattern first — not a rule that MongoDB never joins.
Practice
This join exists because users and orders were referenced, not embedded.