intermediate
Schema design
Choose embedding or referencing by read locality, write contention, document growth, and consistency boundaries.
MongoDB schema design is the choice between embedding related data in one document versus referencing it by identifier. The decision follows read locality, write contention, document growth, and consistency boundaries — not SQL normalization reflexes.
// Embed: product snapshot on order — read once at checkout
{ orderId: 1, items: [{ productId: 9, title: "Mug", price: 12 }] }
// Reference: author on many posts — update profile without rewriting posts
{ postId: 1, authorId: "u_42", title: "..." }
// separate users collection; fetch or $lookup when needed
| Prefer embedding | Prefer referencing | |------------------|-------------------| | One-to-few, read together | One-to-many with unbounded growth | | Data owned by parent aggregate | Shared entity updated independently | | Snapshot semantics acceptable | Strong cross-aggregate consistency | | Bounded array size | Need separate indexes per entity type |
Hybrid patterns are common: embed a snapshot, reference live data; bucket time series into daily documents; use materialized summary collections for dashboards.
On interviews: describe one relationship in the product and defend embed vs reference with concrete read/write flows.
Common pitfalls: embedding unbounded comment lists; referencing then N+1 querying without batching or `$lookup`; duplicating mutable data everywhere; using transactions to paper over a fixable modeling mistake.
The trade-off is read simplicity versus update fan-out — embedding optimizes the happy read path; referencing keeps shared entities maintainable at the cost of joins or extra round trips.
Checklist:
- Classify relationships as one-to-few vs one-to-many.
- Estimate document growth and hot write fields.
- State consistency needs across aggregates.
- Mention denormalized snapshots and when they expire.