Embed vs Reference Modeling Lab (Interactive)
Embed comments until the 16MB BSON wall rejects the write, or split and pay the lookup. Embed comments in a post document until the BSON limit rejects your write, or reference them and measure the extra round-trip — then go viral and see which model breaks.
MongoDB Modeling: Embed Comments vs Reference Them
Grow a post from 100 to a million comments and hit the 16MB BSON wall with one button.
Embedding is winning right now: bounded 1:Few data, read together with the post, one disk read, atomic single-document update. This is the “data accessed together is stored together” sweet spot.
How It Works Under the Hood
Document databases ask one question: what should the common read fetch in a single pass? Bounded 1:1 or 1:few data — a post with its twenty comments — embeds cleanly and lands in one disk read. Unbounded 1:many or 1:squillions relationships must be referenced, because BSON documents hard-cap at 16MB and every write re-copies the whole embedded array regardless of how small the change is. Referencing restores unbounded growth at the price of an extra query per page view. Model the cardinality and the growth, not the aesthetics.
Core Architectural Principles
- Embedded subdocuments share one disk page: a single read assembles the full aggregate and a single write commits it atomically.
- The 16MB BSON cap makes unbounded embedded arrays a time bomb — WriteCommandError arrives exactly when the post goes viral.
- Referenced collections restore unbounded growth and per-comment write cost but charge an extra lookup the application must join.
For document modeling interviews, decide by cardinality: embed 1:1 and 1:few, reference unbounded or M:N. Cite the 16MB limit and whole-document rewrite cost as the embed failure mode, and mention deliberate denormalized copies of frequently read fields inside documents. Close with "model for your query patterns" to show intent.
Embedding wins single-read completeness until array growth hits the document ceiling; referencing wins unbounded scale at the cost of application-side joins.