SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Document Databases

Store each record as a flexible JSON-like document (MongoDB, DynamoDB).

⏱ 12 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A document database stores each record as one document: a flexible, JSON-like object that can hold nested fields and lists. Documents live in collections.

  • Data that is used together is stored together, so one read often gets everything.
  • No fixed table shape: two documents in the same collection can have different fields.
  • Built to scale out across many machines. MongoDB, Couchbase, Firestore and DynamoDB (in document mode) are common examples.

02Concept: What is it?

In a relational database, one order might be spread across three or four tables. In a document database, you can store the whole order as one JSON-like document: the customer, the address and the list of items, all inside it. That is called embedding.

Each document has an _id (a unique key). You can query by other fields too, and add indexes on them. Because the shape is not forced, you can add a new field to new documents without changing the old ones. This is often called being schema-flexible. (You still have a schema in your code. The database simply does not force it by default, although most let you add validation rules.)

A document
Collection: orders
📄Document 9001Asha, 3 items
📄Document 9002Ben, 1 item, gift note
📄Document 9003Chen, 7 items, coupon
→↓open one
Inside 9001
🔑_id: 9001
👤customer: { name, city }
📦items: [ {...}, {...}, {...} ]
Everything the order page needs sits in one place. The list of items is nested inside.
🧠The key question
Embed or reference? Embed data that is read together and stays small. Reference (store an id) data that is shared, changes on its own, or can grow without limit.

03Real-Life Example

🍵The Patient Folder
A clinic keeps one paper folder per patient. Inside are the notes, the allergies, the last three test results and a list of medicines. The doctor opens one folder and sees everything. Two folders do not need the same pages: one patient has a surgery report, another has none. But the folder of all lab results for the whole clinic is kept in a separate cabinet, and each folder only holds a reference number.
Clinic
Document database
A cabinet of patient folders
A collection
One folder
One document
Pages inside the folder
Embedded fields and arrays
Folder number
_id (primary key)
Different pages in different folders
Flexible schema
"See lab file 5512" written on a page
A reference (an id to another document)
An index card sorted by surname
A secondary index
Opening one folder is quick
One read gets the whole document
Two ways to model a blog post
Embed
📄posttitle, text, 5 comments inside
1 read, small list only
Reference
📄posttitle, text
←postId
💬commentsmany documents
2 reads, list can grow forever

04Why Do We Need It?

📦One read, one answer
A page that needs an order, its items and the customer can be served from a single document.
🔄Flexible shape
New fields and different shapes need no big migration. Good while the product is changing fast.
🧩Matches your objects
A JSON document maps closely to objects in your code. Less translation.
📈Scale out
A document is a natural unit to spread across machines (sharding by key).
🧭Varied items
A catalogue where a shirt has size and a laptop has RAM fits well, because each document carries its own fields.
⚡Fast development
Start storing data without designing every table first.
Store things the way your application reads them.

05Where Do We Use It?

🛍️Product catalogues
Items with different attributes, read as a whole.
👤User profiles and settings
One document per user, read at login.
📰Content and CMS
Articles, pages and comments with rich, nested content.
📱Mobile and web back ends
Quick start, offline sync (for example Firestore).
🛰️Event and log data
Records with changing fields, often with time-based expiry.
🎮Game state
A player's whole save is one document.

06Types / Parts / How It Works

Modelling choices

ChoiceWhat it meansUse when
EmbedPut the related data inside the document.Read together, small, owned by this document (an order and its lines).
ReferenceStore the id of another document and fetch it separately.Shared by many, changes on its own, or grows without limit (users, products, comments).
Copy a few fields (extended reference)Embed only the fields you show often, like the product name, and keep the id too.You want fast reads and can accept that the copy may be slightly old.
BucketGroup many small items into one document, for example one document per hour of readings.Lots of tiny records, such as time-based data.
Embedding
Together
  • One read for the whole thing
  • One document write is atomic
  • Copies can go stale
  • Large arrays make big documents
Referencing
Linked
  • Each fact stored once
  • Updates are small
  • Needs several reads or a $lookup
  • No foreign-key checks by default

Families of document stores

ProductNotes (general idea, varies by version)
MongoDBBSON documents, rich queries, aggregation pipeline, multi-document transactions, 16 MB document limit.
Amazon DynamoDBItems found by key. Fast and managed. Items are limited to 400 KB. Query by key plus a few indexes.
Couchbase / CouchDBJSON documents with sync features. Couchbase also offers a SQL-like language (N1QL).
FirestoreManaged, real-time updates, built for mobile and web apps.
Scaling a document database
🧭Routeruses the shard key
→↓
🧱Shard Aids 0-4
🧱Shard Bids 5-9
🧱Shard Cids a-f
Routing Data
Documents are spread by a shard key. Each shard also keeps replicas for safety.
VisualizerEmbed or reference: count the reads and writesChoose a model and a task. Then drag the sliders: more orders makes a rename expensive when embedded, and more comments blows up an embedded list.
How do you model the order?
What do you do?
One collection: orders
orders / 9001
{
  _id: 9001,
  customer: { name: "Asha", city: "Pune" },
  items: [
    { sku: "P1", name: "Product 1", qty: 1 }
    { sku: "P2", name: "Product 2", qty: 1 }
    { sku: "P3", name: "Product 3", qty: 1 }
    ... 2 more
  ]
}
Documents read
1
Round trips
1
to the database
Documents written
0
Main doc size
4 KB
Everything the page needs lives inside one document, so one read returns it all. This is the main strength of embedding: data that is used together is stored together.

A simplified model with fixed sizes (about 400 bytes per item or comment) and counts, no timers or random numbers. Rule of thumb: embed what is read together and stays small. Reference what is shared, changes on its own, or can grow without bound.

07How to Use It / Steps / Implementation

Modelling for a document database

  1. 1
    Start from the queries
    List the screens and API calls. What does each one need to read?
  2. 2
    Embed what is read together
    An order with its line items is the classic case.
  3. 3
    Reference what is shared or grows
    Users, products and long lists of comments get their own documents.
  4. 4
    Bound every array
    If an array can grow without a limit, move it out into its own collection.
  5. 5
    Pick a good key
    For a sharded system, the shard key should spread data and match your common queries.
  6. 6
    Index the fields you filter by
    Without an index a query scans every document in the collection.
  7. 7
    Add validation
    Declare required fields and types so mistakes are caught early.
A document and a query (MongoDB style)
{
  "_id": 9001,
  "customer": { "name": "Asha", "city": "Pune" },
  "items": [
    { "sku": "P1", "name": "Book", "qty": 1, "price": 12 },
    { "sku": "P2", "name": "Pen",  "qty": 3, "price": 3 }
  ],
  "status": "paid"
}

db.orders.createIndex({ "customer.name": 1 })
db.orders.find({ "customer.name": "Asha", status: "paid" })
💡Design for reads, but think about updates
Embedding makes reads quick. Before you copy data into many documents, ask how often it changes and who must see the change at once.

08Key Terms to Know

TermMeaning in easy words
DocumentOne record stored as a JSON-like object with nested fields
CollectionA group of documents, like a table but without a forced shape
_idThe unique key of a document
EmbeddingStoring related data inside the same document
ReferenceStoring the id of another document instead of copying it
Schema-flexibleDocuments in a collection may have different fields
BSONThe binary form of JSON that MongoDB stores
Secondary indexAn index on a field other than the key, to speed up queries
Shard keyThe field used to decide which machine stores a document
Aggregation pipelineA series of stages (filter, group, sort) that process documents
$lookupA MongoDB stage that joins documents from another collection

09Pros, Cons and Trade-offs

✅ Pros
  • Fast reads for data used together
  • Flexible shape, easy to evolve
  • Natural fit with JSON and objects
  • Scales out across machines
  • Quick to start
⚠️ Cons
  • Copies of data can drift apart
  • Joins are limited or slower than in SQL
  • Documents have a size limit
  • Weaker built-in guarantees across documents (varies, transactions exist but cost more)
  • Flexible does not mean careless: messy data can pile up

Trade-offs

ChoiceWe gainWe lose
EmbedOne quick read, atomic writeCopies, big documents, hard to share
ReferenceOne source of truth, small documentsMore reads and app code
Flexible schemaFaster changeLess protection from bad data
More indexesFaster queriesSlower writes, more memory
Multi-document transactionsCross-document correctnessMore overhead and less scale

10Common Problems and Mistakes

Common mistakes

  1. Modelling it like SQL tables. Reference everything, then do many lookups, and lose the main benefit.
  2. The unbounded array. Comments or events embedded forever make huge documents.
  3. Embedding data that is shared. A product name copied into a million orders is hard to change.
  4. No indexes. Every query becomes a full collection scan.
  5. A bad shard key. A key such as the creation date sends all new writes to one shard (a hot shard).
  6. No validation. The same field becomes a string in one document and a number in another.
  7. Using it for heavy, multi-table reports. A relational or analytics system fits better.

Things to watch

📏Size limits
MongoDB: 16 MB per document. DynamoDB: 400 KB per item.
🕰️Stale copies
Copied fields may be out of date. Decide if that is fine.
🔥Hot partitions
One popular key can overload one machine.
🔍Query limits
Some stores (like DynamoDB) only allow queries your keys and indexes support.

11Real-World Examples

🍃MongoDB
A widely used document database, offered self-hosted and as the Atlas cloud service.
⚡DynamoDB
AWS's managed key and document store, built for very high scale and steady low latency.
🔥Firestore
Google's document database for mobile and web, with live listeners.
🛋️Couchbase and CouchDB
Document stores with sync and caching features.
🛒Catalogues and profiles
Many retail and media companies keep product and user data as documents.
🌐Compatibility APIs
Some cloud services expose a MongoDB-compatible API on top of other engines.
📝Note
These are general ideas. Limits, features and names change between versions.
Mini case: a product catalogue
🧑‍💻Product page
→↓get by id
🍃Document DBone document per product
⇢⇣stream of changes
🔍Search index
Each product is one document with its own fields. The product page needs a single read.

12Related Topics to Read Next

Common Database Types→

Where document stores fit among the families.

SQL vs NoSQL→

The big choice behind picking a document store.

Relational Databases→

The other way to model connected data.

Denormalization→

Embedding is denormalization on purpose.

Sharding→

How documents are spread across machines.

Indexing→

Without indexes, queries scan every document.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: JSON-like documents in collections, found by _id or indexed fields.
  • ✔Strength: one read returns data used together. Flexible shape.
  • ✔Embed: small, bounded, read together, owned by the parent.
  • ✔Reference: shared, changing, or unbounded data.
  • ✔Limits: MongoDB 16 MB per document, DynamoDB 400 KB per item.
  • ✔Scale: shard by a good key, replicate each shard.
  • ✔Watch: unbounded arrays, stale copies, missing indexes, hot shards.
  • ✔One line: “Store data the way you read it: together if it is used together.”
← Previous
Relational Databases
Next →
Key-Value Databases