Flexible, nested records
Records have varying shapes and are read whole (a product, a profile).
Say it like this
Each record is read and written as a whole and its shape varies by type, so I store it as one JSON document and index only the fields we query, which avoids a join per read and a migration per new field.
Basic solution
Store each record as a JSON document and index the fields you query.
One document per video, indexes on queried paths
The watch page reads one document and gets the video plus its renditions. Only the fields that queries filter on carry an index; everything else is free-form inside the document.
How it works
- A document is a self-contained JSON-like record (BSON in MongoDB, JSONB in Postgres) holding nested arrays and objects: a product with its variants inside it, a profile with its settings inside it.
- A write stores or replaces the whole document, or patches paths inside it ($set changes one field, $push appends to an array). The engine keeps the whole document contiguous on disk, so a read fetches it in one go without visiting other tables.
- Secondary indexes are declared on paths inside the document (user.email, tags[]) and work like any B-tree index: the index maps the value at that path to the document's location. A query that filters on a path with no index has to scan every document.
- Collections have no enforced schema by default, so two documents in the same collection can have different fields. Optional JSON Schema validation rejects documents that do not match a declared shape.
- Scaling is by sharding on a shard key, same rules as any partitioned store: each shard holds the documents whose key hashes into its range, so choose a key the hot queries filter on or every query fans out to every shard.
- Transactions across documents exist but are slower and rarer; the design goal is that one document is the unit of consistency, so a single write changes everything that must change together.
Why it fits whole-record access
- The data arrives and leaves as one object, so no join and no object-relational mapping.
- Different record types in one collection can carry different fields without a schema change.
Worked example
Video metadata as documents
- 500K uploads/day, about 1B videos after 5 years. Each video document: id, owner, title, description, status, visibility, renditions[] (5 entries × ~120 B), thumbnails[], stats summary ≈ 2 KB.
- Storage: 1B × 2 KB = 2 TB, plus indexes on owner_id, status and (visibility, published_at) at roughly 15% ≈ 2.3 TB total. Sharded on video_id hash across 4 shards of about 600 GB each, so each shard's hot subset fits in memory.
- Reads: the watch page needs the whole document once: one fetch by _id ≈ 1 ms, no join to a renditions table, because the renditions are inside the document.
- Writes: the transcoding pipeline patches renditions[] and status as each rendition lands ($push + $set), five small updates per video, 30 writes/s across the fleet. Trivial.
- Queries that stay fast: "my videos" (owner_id index, sorted by created_at), "public videos published this week" (compound index on visibility and published_at).
- Query to keep out: "videos with rendition 4K and bitrate > X" across everything. There is no index on a field inside the renditions array, so it would scan 1B documents; that is analytics, so ship it to the OLAP copy.
Variants and when each wins
MongoDB
Postgres JSONB
- A JSONB column next to ordinary columns, with GIN indexes on paths and full transactions. It wins when most data is relational and a few fields are flexible, and loses when every query digs into the JSON, because the planner has less to work with.
DynamoDB with document attributes
- Items up to 400 KB with nested maps and lists, queried only by partition and sort key plus declared indexes. It wins when you want a managed, fast store and your queries are key lookups; the model is key-value, not document search.
Couchbase / CouchDB
- Document stores with a built-in caching tier and, for CouchDB, replication to mobile devices for offline use. They win in those niches, mobile sync especially.
Default to Postgres with JSONB when the system already runs Postgres; pick MongoDB when documents are the primary model and you want sharding without running a router yourself.
Failure modes
Schema drift
- You notice code crashing on a document that is missing a field newer documents have. It happens because nothing enforces the shape, so three versions of the document have accumulated in one collection. Turn on JSON Schema validation for writes, put a version field in every document, and upgrade old documents lazily when they are read.
Unbounded array growth
- You notice one document growing to megabytes (a post with 100K comments inside it) and every read of it taking hundreds of milliseconds. It happens because a one-to-many relationship with no upper bound was embedded inside the parent. Embed only lists with a known small bound; put comments in their own collection keyed by post_id.
Query on an unindexed path
- You notice a new feature filtering on a nested field and the whole collection being scanned. It happens because documents hide which fields are queried, so nobody added the index when the feature shipped. Index the path, or in Postgres add a GIN index on the JSONB column, and review the slow-query log after each feature.
Write amplification on patches
- You notice a small $set rewriting a large document and taking as long as a full replace. It happens because the engine stores the document contiguously, and a change that makes it larger forces it to be moved and rewritten in full. Keep documents to tens of KB, and split fields that change constantly (view counts) into a separate small document or a counter.
Cross-document consistency
- You notice a transfer between two documents half-applied: the debit is there and the credit is not. It happens because writes to two documents are not atomic by default, and the process failed between them. Model the data so one document is the unit of change, or use the engine's multi-document transaction and accept that it is slower.
Interviewer follow-ups
Answer out loud before you open each one.
When is a document store the wrong choice?
When the same data is read in many shapes and joined often, such as orders with customers and products in reports; relational wins. Also when records are unbounded time-ordered streams, where wide-column fits better.
Embed or reference?
Embed when the child list is bounded, read with the parent, and updated with it, like renditions of a video. Reference with a separate collection when the list is unbounded or queried on its own, like comments. The question is really "what is the unit of read and write".
How do you evolve the schema without downtime?
Add a schema version field, write new documents in the new shape, make reads tolerate both shapes, and migrate old documents lazily on read or with a background job. Validation rules are tightened only after the backfill finishes.
Postgres JSONB or MongoDB?
If most of the data is relational and you need transactions across it, JSONB in Postgres gives flexible fields without a second system. If the document is the whole model, you need sharding at tens of TB, and the team is ready to run it, MongoDB is built for that.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 | Transcoder | Compute Engine | Azure Virtual Machines | DigitalOcean Droplets, any VM or bare metal |
| Amazon DynamoDB | Shards by _id hash | Firestore, Bigtable | Cosmos DB | ScyllaDB, Apache Cassandra |
| Amazon Redshift | Analytics copy | BigQuery | Synapse Analytics, Microsoft Fabric | ClickHouse, Snowflake, Apache Druid |