ModelingIntermediate
Embed or reference in a document database?
“How do you decide whether to embed a relationship or reference it by id?”
What this tests
- Document data modeling
- Cardinality and growth awareness
Answers by level
Read the beginner answer first and notice what is missing.
Embed when the child is read with the parent, bounded in number, written with the parent, and should be a snapshot: order line items, a shipping address. Reference when the child is unbounded, queried on its own, shared by many parents, or mutable in a way that must be visible everywhere: comments on a post, the author of many posts.
The traps: embedding an unbounded array blows past the document size limit and drags the whole history into every read; referencing everything reproduces a relational schema without joins or transactions.
Green flags · Red flags
Strong green flag · Says "if every query needs $lookup, you wanted a relational database".
Green flags
- Bounded + read-together → embed; unbounded/shared → reference
- Knows the 16 MB limit
- Snapshot vs mutable distinction
Red flags
- Embed everything regardless of growth
- No awareness of the document size limit
Follow-up questions
F1
Post has 100k comments — embed or reference?
Scenario
An orders collection embeds an ever-growing array of status-change events. What goes wrong and what do you change?