# MongoDB for system design interviews

> MongoDB is a document database that stores BSON documents in collections and supports indexes, aggregation, and transactions. It fits systems where related data can be read and updated together as a document, with replica sets for availability and sharding for horizontal scale.

Source: https://sysround.com/tech/mongodb
Updated: 2026-11-05


## How it works

A MongoDB deployment contains databases, collections, and BSON documents. Documents can contain nested objects and arrays, so data that is commonly accessed together can be embedded rather than joined at read time. Model around access patterns, while keeping document growth bounded.

WiredTiger, the default storage engine, uses a cache, B-tree-based storage structures, checkpoints, and a journal for crash recovery. It provides document-level concurrency control and uses optimistic concurrency internally. Every additional index consumes storage and cache space and adds work to writes.

A replica set has one primary that accepts writes and secondaries that asynchronously replicate changes from the primary's operation log, called the oplog. Eligible members can elect a new primary after failure. Replication provides redundancy, but a write's durability across failover depends on its write concern.

A sharded cluster distributes collection data across shards, normally with each shard deployed as a replica set. Applications connect through mongos routers, which use metadata from the config server replica set to route requests. Queries that identify the relevant shard-key values can target fewer shards; other queries may require scatter-gather.

MongoDB divides sharded data into ranges of shard-key values and migrates ranges between shards to balance distribution. Range sharding preserves useful locality, while hashed sharding spreads values more evenly but weakens range targeting on the hashed field. The shard key determines both write distribution and which queries remain efficient.

## What it gives you in a design

- **Document modeling and validation.** Embed bounded related data for single-read retrieval and atomic updates. Collections can enforce schema validation, so flexible documents do not have to mean unchecked data.
- **Indexes and query planning.** Compound, multikey, partial, unique, and geospatial indexes support different access patterns. Design indexes around filters, sorts, and pagination, then inspect execution plans rather than assuming an index makes a query cheap.
- **Atomic updates and transactions.** Updates to one document are atomic, including changes to multiple fields or embedded elements. Multi-document transactions are available across replica sets and sharded clusters, but introduce coordination, contention, and retry costs.
- **Aggregation pipelines.** Pipelines support filtering, grouping, transformation, and joins through stages such as $lookup. Large aggregations and cross-shard joins still consume substantial resources, so precomputed views may be better for frequent expensive queries.
- **Explicit consistency controls.** Read preference selects eligible replica members, read concern controls visibility guarantees, and write concern controls acknowledgment requirements. These are separate choices, not one strong-versus-eventual consistency switch.
- **Change streams.** Change streams expose committed data changes from replica sets and sharded clusters for downstream processing. Consumers should persist resume tokens and make side effects idempotent; recovery depends on retaining enough oplog history.
- **TTL expiration.** TTL indexes asynchronously delete expired documents, which is useful for sessions and temporary records. Expiration is not a precise deadline, so application logic must reject expired holds or credentials even before deletion occurs.

## Scaling, replication and failure

Start by sizing a replica set for the working set, index footprint, and write rate. Secondary reads can offload suitable read traffic, but secondaries may lag and every data-bearing replica still applies the write stream. Replication does not partition write load.

Shard when storage or workload exceeds what one replica set can handle. Choose a shard key with sufficient cardinality, reasonably even traffic, and alignment with important queries. A monotonically increasing range key can concentrate inserts on one shard, while a single hot shard-key value remains a bottleneck even with hashing.

Choose consistency per operation. Majority write concern protects acknowledged writes against rollback during ordinary failover, while weaker acknowledgment can lose acknowledged writes. Majority read concern alone does not guarantee the latest value; causal sessions and linearizable reads address different ordering and freshness requirements.

During primary failure, writes pause until election and recovery complete. A replica-set partition without a voting majority cannot elect a writable primary, so region placement determines both latency and outage tolerance. Use bounded retries and idempotent operations because a timeout may leave the outcome of a write unknown.

## Limits and defaults worth knowing

- **Maximum BSON document size:** 16 MiB per document. Store large files in object storage or use GridFS when MongoDB-managed file storage is required.
- **Maximum nesting depth:** 100 levels of nesting in BSON documents, including nested objects and arrays.
- **Indexes per collection:** A collection can have at most 64 indexes.
- **Fields in a compound index:** A compound index can contain at most 32 fields.
- **Transaction lifetime:** The default transaction lifetime limit is 60 seconds. It is configurable, subject to deployment restrictions.
- **Replica-set membership:** A replica set supports up to 50 members, with at most 7 voting members.

## Use it when

- Entities have variable attributes, such as marketplace listings, and most reads retrieve a bounded entity with its related fields.
- Important invariants fit inside one document and can be enforced with atomic conditional updates.
- The workload needs indexed document queries rather than only primary-key lookups.
- Horizontal partitioning is necessary and you can identify a shard key that distributes traffic without making core queries scatter-gather.
- Database changes need to feed search indexes, caches, or asynchronous processing through change streams.

## Avoid it when

- The core workload depends on frequent joins across many entities, relational constraints, and broad multi-row transactions. A relational database is often simpler.
- One unbounded document or a few extremely hot records dominate writes. Adding shards does not split concurrent updates to one document.
- The main workload is large analytical scans and aggregations over historical data. A columnar warehouse is usually a better fit.
- The requirement is accepting conflicting writes to the same records in every region during network partitions. Standard MongoDB replica sets use a single writable primary, not multi-primary conflict resolution.

## What interviewers ask about it

### How would you choose the shard key?

Start with the highest-volume queries and writes, then evaluate cardinality, skew, monotonic growth, and routing selectivity. Explain the trade-off between distributing writes and keeping related reads on one shard, including what happens for a very large tenant or hot entity.

### When would you embed data instead of referencing it?

Embed data that is read together, has bounded growth, and benefits from atomic updates with its parent. Reference independently updated or unbounded data, such as a post's complete comment history, to avoid oversized documents and write contention.

### Can an acknowledged write disappear after failover?

A write acknowledged only by the primary can be rolled back if that primary fails before replication makes the write durable on the surviving majority. Use majority write concern for important state, and handle timeouts as potentially successful operations rather than automatically treating them as failures.

### Does reading from the primary guarantee the latest data?

Primary read preference chooses where a read goes; it does not by itself establish a linearizable guarantee. For supported single-document reads that require real-time ordering, consider linearizable read concern with majority writes, and accept the additional coordination and availability costs.

### How would you prevent overselling or duplicate claims?

Use an atomic conditional update that changes inventory only if the required quantity remains, or use a unique constraint for a one-time claim where the indexing rules permit it. If the invariant spans documents, use a transaction or redesign the aggregate, and use an idempotency key for retries.

### How would you keep a search index synchronized?

Consume change streams, checkpoint resume tokens after successful processing, and make index updates safe to replay. Monitor consumer lag against available oplog history and define a snapshot-and-rebuild path if the consumer can no longer resume.

## Common mistakes

- Calling MongoDB schemaless and skipping schema validation, migration planning, and document-growth limits.
- Assuming secondary reads are current or that majority read concern is the same as linearizability.
- Choosing a shard key only for even storage distribution while ignoring hot writes and scatter-gather queries.
- Treating transactions, TTL deletion, or change streams as automatic solutions for business invariants, exact deadlines, or exactly-once external effects.

## Alternatives

- **PostgreSQL:** Prefer it when relational constraints, joins, and multi-row transactions dominate. JSONB can handle flexible attributes without abandoning a relational model.
- **DynamoDB:** Prefer it for managed key-value and document access with well-defined partition-key queries, when its indexing and transaction constraints fit the workload.
- **Cassandra:** Prefer it for partition-oriented workloads requiring distributed writes and tunable consistency, especially when multi-region write availability matters more than rich queries or cross-record transactions.
- **Elasticsearch:** Prefer it for relevance-ranked full-text retrieval and search-oriented aggregations, typically as a derived index alongside a primary database.

## Interview questions where it comes up

- [Design Facebook Marketplace](https://sysround.com/questions/design-facebook-marketplace): Flexible listing attributes fit document modeling, while location queries and tenant or regional skew expose indexing and shard-key trade-offs.
- [Design Google Photos](https://sysround.com/questions/design-google-photos): MongoDB can store searchable photo and album metadata while the actual media remains in object storage.
- [Design a chat app like WhatsApp](https://sysround.com/questions/design-whatsapp): Message persistence raises concrete questions about bounded documents, conversation-based partitioning, ordering, and durable write acknowledgment.
- [Design a restaurant review app like Yelp](https://sysround.com/questions/design-yelp): Geospatial discovery and review documents fit its query capabilities, while rating updates require explicit consistency and aggregation choices.
- [Design Wikipedia or Notion](https://sysround.com/questions/design-wikipedia): Document metadata and version records illustrate conditional updates, bounded embedding, and transactions for related state changes.

## FAQ

### What are the main components of MongoDB architecture?

A replica set consists of a primary and members that replicate data and participate in failover according to their configuration. A sharded cluster adds multiple shards, mongos query routers, and a config server replica set. Each shard is normally a replica set, separating data distribution from replication.

### What is the difference between MongoDB replication and sharding?

Replication keeps copies of the same data for availability and recovery. Sharding divides data among different replica sets to spread storage and workload. Adding replicas does not distribute primary write ownership the way adding shards can.

### Is MongoDB ACID compliant?

MongoDB supports atomic single-document operations and ACID multi-document transactions, including transactions across shards. Transaction guarantees depend on the selected read and write concerns, and snapshot isolation should not be confused with serializable isolation. Transaction support does not remove the need to design invariants and handle retries correctly.

## Related concepts

- [Database sharding](https://sysround.com/concepts/database-sharding)
- [Database replication](https://sysround.com/concepts/replication)
- [Denormalization](https://sysround.com/concepts/denormalization)
- [Database indexing](https://sysround.com/concepts/database-indexing)
- [SQL vs NoSQL](https://sysround.com/concepts/sql-vs-nosql)


---
SysRound (https://sysround.com) is an AI practice tool for system design interviews: a voice or typed AI interviewer, a shared whiteboard, then feedback on every skill and a model answer. Its feedback is AI-generated and can be wrong.
