MongoDB Subset and Computed Patterns
Fast recall
Quick revision
Core answer
Whether you recognize the write-time denormalization idiom that makes read-heavy MongoDB workloads fast
Embedding unbounded arrays leading to 16MB overflow, or recomputing aggregates on every read
Show both patterns composed together, explain staleness handling with background refresh, and cite real examples (product reviews, leaderboards)
Interview-ready guide
Interview answer
Frame both patterns
- Subset keeps only the hot slice in the main document, tail in a side collection
- Computed stores pre-calculated aggregates so reads never recompute
- Both trade a bit of write complexity for much cheaper reads
Show the idioms
$pushwith$sliceand$sortfor subset$incfor counters; background$mergefor heavier aggregates- Index the hot slice fields if you query them
Call out the trade-offs
- Write-heavy workloads can flip the math
- Staleness is acceptable for most aggregates; design refresh cadence
- Compound failures — wrap in transaction or run nightly reconcile
Wrap up
- Both exist because the 16MB limit plus working-set economics punish unbounded embedding
- Combine them —
productswithrecentReviewsslice plusratingAvgcomputed field is a canonical shape
MongoDB Subset and Computed Patterns
Direct Answer
The subset pattern keeps a hot slice of a growing array (last 10 reviews, recent 20 comments) in the primary document and moves the tail to a separate collection — so the main document stays small and fast to load. The computed pattern stores pre-calculated values (averages, totals, rankings) alongside the raw data so reads never recompute on the fly. Both patterns trade a bit of write complexity for dramatically cheaper reads, and both exist because MongoDB's 16MB document cap plus working-set economics punish unbounded embedding. Use subset when 90% of reads want only the recent slice; use computed when the same aggregation runs thousands of times per read.
Common Mistakes & Pitfalls
Embedding unbounded arrays leading to 16MB overflow, or recomputing aggregates on every read
Check your understanding
Answer these without looking back at the article.
- How do you keep the subset in sync when an old review is edited or deleted?
- When does computing aggregates via `$merge` beat updating them inline on each write?
- How do MongoDB transactions help keep subset and source consistent?
- What's the trade-off between embedding recent items vs a full materialized view collection?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.