MongoDBInterview Questions

MongoDB Interview Questions

A curated set of questions that come up repeatedly in MongoDB interviews, from fundamentals through operational topics — with concise, accurate answers you can actually reason about, not just memorize.

Document Model & BSON
  1. What is a document, and how does it differ from a row? A document is a BSON object (superset of JSON) that can nest arrays and sub-documents to arbitrary depth. Unlike a row, documents in the same collection can have different fields — there is no fixed schema unless you add validation.

  2. Why BSON instead of JSON? BSON adds types JSON lacks (ObjectId, Date, binary data, Decimal128, distinct int/long/double) and is a binary format designed for fast traversal and encoding/decoding, at the cost of being slightly larger than minified JSON.

  3. What is the maximum document size, and why does it exist? 16 MB. It exists to prevent a single document from monopolizing RAM and network bandwidth, and to keep replication/indexing efficient.

  4. What is an ObjectId made of? A 12-byte value: a 4-byte timestamp, a 5-byte random value (unique per process), and a 3-byte incrementing counter. It is roughly sortable by creation time and globally unique without coordination.

  5. Does every document need an _id? Yes — MongoDB automatically generates an ObjectId _id if one isn’t supplied. It is always indexed and unique per collection.

Schema Design
  1. When do you embed vs reference? Embed when data is small, bounded, and always read together with its parent. Reference when data is large/unbounded, shared across many parents, or updated independently. See the Embedding vs Referencing page.

  2. What is the "one-to-squillions" problem? A one-to-many relationship where the "many" side is effectively unbounded (sensor readings, log events). Embedding it directly risks hitting the 16MB limit and causes expensive document rewrites — model it with a parent reference instead.

  3. Name three MongoDB schema design patterns. Attribute pattern (sparse/varying fields), bucket pattern (time-series grouping), and computed pattern (precomputed aggregates) are common answers — polymorphic, outlier, and subset patterns are also valid.

Indexes
  1. What index types does MongoDB support? Single field, compound, multikey (arrays), text, geospatial (2d/2dsphere), hashed, wildcard, and TTL indexes.

  2. Explain the ESR rule. Order compound index fields as Equality fields, then Sort fields, then Range fields — this maximizes the query shapes a single compound index can serve efficiently.

  3. What does .explain("executionStats") tell you? Whether the query used an index (IXSCAN) or scanned the whole collection (COLLSCAN), how many documents were examined vs returned, and the winning plan chosen by the query planner.

  4. What is a covered query? A query where every field it needs (filter + projection + sort) is present in the index itself, so MongoDB never has to fetch the actual document — explain() shows totalDocsExamined: 0.

  5. Unique vs partial index — what’s the difference? Unique enforces no duplicate values (treating missing/null as one value); partial only indexes documents matching a filter expression, and can carry a unique constraint scoped to that subset.

Aggregation
  1. What does $lookup do? Performs a left outer join against another collection in the same database, adding matched documents as an array field.

  2. $match vs find() — when do you need aggregation instead of a simple query? Use aggregation when you need grouping, joins ($lookup), reshaping, or multi-stage transforms that a single find() filter/projection cannot express.

  3. Why put $match early in a pipeline? Stages run in order — filtering early reduces the number of documents flowing into (and processed by) every subsequent stage, and lets the planner use indexes for that initial match.

  4. What does $unwind do, and what is a footgun with it? It outputs one document per array element. The footgun: unwinding a large array multiplies document count dramatically, and an empty/missing array drops the document entirely unless preserveNullAndEmptyArrays: true is set.

Replication & Sharding
  1. What is a replica set? A group of mongod processes maintaining the same data set, with one primary accepting writes and secondaries replicating via the oplog. It provides high availability and automatic failover.

  2. How does failover work? If the primary becomes unreachable, remaining members hold an election (based on the Raft-like protocol) and promote a new primary, typically within seconds.

  3. What is a shard key, and why is choosing it hard to undo? The field(s) used to distribute documents across shards. A poorly chosen shard key (low cardinality, monotonically increasing) causes uneven data distribution or write hotspots, and changing it historically required a full data migration (though newer versions support limited shard key reshaping).

  4. What makes a good shard key? High cardinality, even distribution of both data and read/write load, and alignment with your most common query patterns so queries can be routed to a single shard (targeted) instead of broadcast to all shards (scatter-gather).

Transactions & Consistency
  1. When do you need a multi-document transaction? When multiple documents (possibly across collections) must be updated atomically — e.g. transferring a balance between two accounts, where a partial write would leave data inconsistent.

  2. What is the difference between read concern and write concern? Write concern controls how many nodes must acknowledge a write before it’s considered successful; read concern controls the durability/consistency guarantee of the data a read returns (e.g. majority only returns data acknowledged by a majority of nodes).

  3. What is causal consistency? A session-scoped guarantee that a client’s own sequence of reads and writes is observed in order (read-your-own-writes), even across different replica set members, using a client session.

Change Streams & Storage Engine
  1. What are change streams built on? The replication oplog — they require a replica set (or sharded cluster) and give applications a push-based feed of insert/update/delete/etc. events.

  2. What is WiredTiger? MongoDB’s default storage engine since 3.2 — it provides document-level concurrency control, compression, and a B-tree-based on-disk format with an in-memory cache for the working set.

  3. What happens if your working set exceeds the WiredTiger cache? MongoDB has to evict pages and re-read them from disk more often, causing increased I/O and latency — a signal to add RAM, shard, or reduce the working set (better indexes, smaller documents).

Topic

One-line takeaway

ObjectId

12 bytes: timestamp + random + counter, roughly time-sortable

Embed vs reference

Driven by access pattern and cardinality, not just relationship shape

ESR rule

Equality, Sort, Range — the compound index field order that maximizes reuse

$lookup

Left outer join in an aggregation pipeline

Shard key

High-cardinality, evenly distributed, aligned to query patterns — hard to change later

Write concern

How many nodes must ack a write

Read concern

What durability guarantee a read observes

Change streams

Real-time event feed built on the oplog, requires a replica set

WiredTiger

Default storage engine — document-level locking, compression, in-memory cache

Note
For a deeper answer to any of these, follow the cross-referenced pages under Data Modeling, Indexes, Aggregation, and Advanced Topics — this page is designed for quick review before an interview, not as a first introduction to any topic.