Courses › System Design › Key Technologies

MongoDB

Document modeling, embedding vs referencing, replica sets and shard keys.

MongoDB is the most widely used document database. It stores JSON-like documents (BSON) in collections, with no fixed schema, rich secondary indexes and a flexible query language. In interviews, it's a reasonable choice when your data is naturally shaped as self-contained documents that are read and written as a whole.

Data model

  • Document — a JSON-like object up to 16 MB, with nested objects and arrays. Every document has a unique _id.
  • Collection — a group of documents, roughly a table. Documents in one collection don't need the same fields.
  • Embedding vs referencing — the central modeling decision.
{
  "_id": "post_123",
  "author_id": "user_42",
  "title": "Designing a URL shortener",
  "tags": ["system-design", "hashing"],
  "comments": [
    { "user_id": "user_7", "text": "Great post", "at": "2026-10-01T10:00:00Z" }
  ]
}

[!TIP] Model for your access patterns The rule of thumb is "data that is accessed together should be stored together." Start from the queries in your API and shape documents so each hot read is a single document fetch.

Indexes and queries

  • Secondary indexes on any field, including compound, multikey (indexing array elements), text, geospatial (2dsphere) and TTL indexes.
  • The aggregation pipeline ($match, $group, $sort, $lookup) handles moderate analytics, but it isn't a data warehouse.
  • Without an index, a query scans the whole collection — the same rules as Database Indexing apply.

Replication and consistency

  • A replica set is one primary and several secondaries. All writes go to the primary; secondaries replicate its operation log (oplog) and can serve reads.
  • If the primary fails, the replicas elect a new one within seconds.
  • Write concern controls durability: w: "majority" waits until most replicas have the write, so it survives a failover.
  • Read preference and read concern control freshness: reading from secondaries scales reads but may return stale data.
  • Multi-document ACID transactions are supported (since 4.0), but they're slower; good schema design keeps most writes to a single document, which is always atomic.

Sharding

[App] -> [mongos router] -> (Shard A: replica set)
[mongos router] -> (Shard B: replica set)
[mongos router] -> (Shard C: replica set)
  • Collections are split across shards by a shard key. A mongos router sends each query to the right shard, or to all of them if the query doesn't include the shard key (a scatter-gather query).
  • Hashed shard keys spread writes evenly; ranged shard keys keep nearby values together for range queries but risk hot spots (e.g. a monotonically increasing timestamp).
  • As with any partitioned store, see Sharding — the shard key is the decision that matters most.

When to use it

  • Content and catalog data with varied attributes (product catalogs, CMS, user profiles)
  • Documents read and written as a unit, where a fixed relational schema would mean many sparse columns or join tables
  • Teams that want a flexible schema plus real secondary indexes

When not to

  • Highly relational data with many-to-many joins and strong integrity constraints — use PostgreSQL
  • Pure key-value access at massive scale — DynamoDB or Cassandra are simpler to scale
  • Heavy analytics — use a columnar store like ClickHouse

[!INTERVIEW] Justify the document model "A listing is always read as a whole — title, photos, amenities, house rules — and its attributes vary a lot by property type. I'll store each listing as one MongoDB document, sharded by a hashed listing_id, with a 2dsphere index on location for map searches."