Databases Reference/NoSQL Families

Document Databases

BSON/JSON documents, embedding vs referencing, schema flexibility trade-offs, secondary indexes, and MongoDB replica sets and sharding at storage depth.

3/5Overview: 25m

Document model storage

A document is a self-contained JSON/BSON record with nested objects and arrays. The database stores it as one blob (plus extracted index keys). Schema is flexible — new fields appear without ALTER TABLE.

Contrast with relational: joins are optional; related data is often embedded in one document.

Embedding vs referencing

PatternStorageReadWrite
EmbedOne doc holds child arraySingle read, no joinUnbounded arrays blow document size (16 MB limit in MongoDB)
ReferenceStore author_id, separate collection$lookup or second queryCheaper updates to child

Rule of thumb: embed what you read together and what has bounded cardinality; reference what grows without limit or changes independently.

Indexes on documents

Secondary indexes extract paths (address.zip, tags) into B-tree structures. Multikey indexes on arrays create index entry per array element — write amplification on array updates.

Partial indexes and compound indexes follow the same leftmost-prefix rules as relational B-trees.

MongoDB storage engine (WiredTiger)

Documents in WiredTiger use B-trees with MVCC (similar snapshot isolation to Postgres). Compression (snappy/zstd) at page level. Oplog is the replication log — capped collection of idempotent operations replayed on secondaries.

Replication and elections

Replica set: one primary, N secondaries. Election on primary loss (Raft-like protocol via Paxos variant). Default write concern w:1 — async replication risk mirrors RDBMS async replicas.

Read concern / write concern tune durability vs latency (majority waits for quorum of replicas — cross-ref Distributed Systems → Quorums).

Sharding in MongoDB

Shard key is immutable after insert. Chunks migrate between shards when imbalanced. Bad shard key (timestamp ascending) → hot shard.

When documents win

  • Evolving schema, heterogeneous records
  • Aggregate-oriented access (load whole "order with line items")
  • Hierarchical data with bounded depth

When they lose

  • Many-to-many with heavy cross-entity queries
  • Strong cross-record transactions (multi-doc ACID exists but has limits)
  • Analytics aggregations across billions of docs (→ warehouse/columnar)

Where this goes next

Wide-Column Stores — partition-key-first design for write-heavy, wide rows at scale.

Further Reading

Hands-On Tasks (Optional)

Low-setup exercises — schema drills, paper walkthroughs, or optional local installs. No autograding; the goal is interview fluency on how data is stored.

  • Embed vs reference for a blog schema

    Blog with posts, comments (unbounded), and authors. Sketch document shapes for embed-comments-in-post vs separate comments collection. Name one read that's faster and one write that's harder for each.

    15m