Notesdata-models🌱 seedling

Document Model

Also: Document Database · Document Store · Document-Oriented Database

Each record is a self-contained tree (usually JSON) that holds its one-to-many children inline. You get locality and a close match to application objects, and pay for it whenever data is shared across documents.

Why it exists

Many records really are trees: a profile owns its jobs, an order owns its line items. Storing the tree whole removes the joins and the Object-Relational Mismatch that rebuilding it from tables would need.

How it works

  • A document is read and written as a unit; one read returns the whole tree (locality).
  • Nested arrays and objects model one-to-many relationships owned by the parent.
  • Many-to-one data (a company shared by many profiles) is either copied into each document (denormalized) or referenced by ID and joined later (MongoDB $lookup).
  • Documents in a collection need not share fields (Schema-on-Read), though validators can enforce a shape.
  • Secondary indexes on nested fields make cross-document queries possible, not free.

Trade-offs

Gains Costs
one read per aggregate; no join to reassemble weak or discouraged joins; many-to-many is awkward
shape matches the code copies drift unless Normalization is applied by hand
flexible, heterogeneous records whole-document writes; size limits (16 MiB in MongoDB)

In practice

  • Embed what the parent owns, what is bounded and what is read together; reference what grows without limit, is shared, or is updated independently.
  • Postgres jsonb gives document storage inside a relational database; any update rewrites the whole value and locks the row, so its docs advise keeping documents small and atomic.

Pitfalls

  • Unbounded arrays (comments, events) grow until reads drag megabytes along and writes hit the size limit.
  • Data that starts as a tree rarely stays one: new features add many-to-many links, and the join logic moves into application code.

Recall

These cards are also in your review deck, scheduled with spaced repetition.