MongoDB Data Modelling: Embed or Reference?
A simple decision guide for when to nest data inside a document and when to link to another collection, with the limits and access patterns to check first.
SmartCampus Buddy TeamSeptember 16, 20266 min read
In a relational database you normalise by default. In MongoDB the first design question is different: should this data live inside the parent document, or in its own collection with a reference?
Start from how the data is read
Model for your queries. If two pieces of data are almost always shown together, storing them together means one read instead of two.
Embed when
- The related data is small and bounded, such as a user's few addresses or a post's handful of tags.
- It is read together with the parent.
- It does not make sense on its own.
{
_id: 1,
name: "Ada",
addresses: [{ city: "Pune", pin: "411001" }]
}Reference when
- The related list can grow without limit, such as all orders or all likes. A document is capped at 16 MB, and huge arrays make updates slow.
- The related data is used from many places.
- It changes independently and often.
Atomicity is a benefit of embedding
Updates to a single document are atomic. If data that must change together is embedded, you often avoid multi-document transactions altogether.
Joining when you must
The aggregation stage $lookup can combine collections, much like a left join. If you find yourself using it on every request, revisit whether embedding would fit the access pattern better.
Do not forget indexes
A good model still needs indexes on the fields you filter and sort by, and a unique index for fields that must be unique, such as an email address.
Key takeaways
- Design for your read patterns first.
- Embed small, bounded, co-read data; reference unbounded or shared data.
- Single-document writes are atomic.
- Add indexes, including unique ones, to match your queries.