MongoDB Interview Questions
NoSQL architecture track: MongoDB document modeling, WiredTiger storage engine, replica set election protocol, sharding keys, and aggregation pipelines.
Practice MongoDB Interview Questions
Showing 16 of 16 technical questions with engineering explanations
How does MongoDB store data as BSON documents, and what practical limits does BSON impose compared to JSON?
Senior Engineering Answer
MongoDB stores records as Binary JSON (BSON) documents rather than plain text JSON. BSON adds rich native types unavailable in JSON—such as ObjectId, Date, Int32, Int64, Decimal128, and BinData—and encodes type and length prefixes so the storage engine can traverse fields in O(1) offsets without parsing entire documents. Every BSON document is capped at 16 MB to prevent excessive RAM consumption and single-operation network stalls; payloads exceeding 16 MB must be split via referencing or stored using GridFS.
// ObjectId (12 bytes): 4B timestamp + 5B random value + 3B counter
const orderDoc = {
_id: new ObjectId(),
totalAmount: NumberDecimal("149.95"), // Decimal128 avoids IEEE-754 float drift
placedAt: new Date(),
status: "confirmed"
};Storing monetary amounts as standard JavaScript floating-point numbers (BSON Double) instead of Decimal128 causes rounding discrepancies in financial aggregations.
What is the difference between findOneAndUpdate, updateOne, and replaceOne in MongoDB?
Senior Engineering Answer
updateOne modifies specific fields using update operators like $set or $inc and returns acknowledgment metadata (matchedCount, modifiedCount) without returning the document itself. findOneAndUpdate atomically finds, updates, and returns either the pre-update or post-update document in a single server round-trip. replaceOne overwrites the entire document (preserving _id) with a new payload containing no update operators, which means omitted fields are deleted.
const updated = await db.collection("inventory").findOneAndUpdate(
{ sku: "KB-900", stock: { $gte: 1 } },
{ $inc: { stock: -1 } },
{ returnDocument: "after" }
);Passing a plain object without $set to updateOne fails, whereas passing a plain object to replaceOne silently wipes out any fields not listed in the replacement object.
When should you model relationships in MongoDB using embedded subdocuments versus normalized document references?
Senior Engineering Answer
Embed subdocuments when related data has a bounded 1:1 or 1:few cardinality, is almost always read together with its parent, and benefits from single-document atomic writes. Use document references (normalized IDs joined at the application layer or via $lookup) when relationships are 1:many with unbounded growth (like activity logs or comments), when child items are frequently queried or updated independently, or when embedding would push documents near the 16 MB BSON limit.
// Good embedding: bounded shipping addresses on a user
// Bad embedding: unbounded array of millions of audit events
{
_id: ObjectId("..."),
email: "ana@example.com",
addresses: [
{ label: "home", city: "Austin", postalCode: "78701" }
]
}Embedding unbounded arrays causes documents to repeatedly outgrow their allocated disk slots and triggers heavy padding/reallocation overhead plus 16 MB BSON cap failures.
How do single-field, compound, and multikey indexes work in MongoDB, and what happens when indexing array fields?
Senior Engineering Answer
MongoDB uses B-tree indexes. A single-field index orders documents by one attribute, while a compound index orders by multiple fields sequentially and supports queries matching any leading prefix of its keys. When you index a field whose value is an array, MongoDB automatically creates a multikey index with a separate index entry for every element in the array. Compound multikey indexes forbid having two array fields in the same index to prevent Cartesian product index explosion.
// Supports queries on { tenantId }, { tenantId, status }, or { tenantId, status, createdAt }
db.orders.createIndex({ tenantId: 1, status: 1, createdAt: -1 });Querying only on the trailing field of a compound index (such as { status: 'paid' } without tenantId) cannot use the compound index prefix and degrades to a collection scan (COLLSCAN).
How do you apply the Equality, Sort, Range (ESR) rule when designing compound indexes?
Senior Engineering Answer
The ESR rule orders keys in a compound index to minimize index keys scanned and avoid blocking in-memory sorts: place fields with exact Equality filters first, fields used in Sort clauses second, and fields used in Range predicates ($gt, $lt, $in, regex) last. Putting a range field before a sort field forces MongoDB to read all matching index entries and perform an expensive in-memory SORT stage capped at 100 MB unless allowDiskUse is enabled.
// Query: db.events.find({ orgId: "acme", createdAt: { $gte: start } }).sort({ priority: -1 })
// Optimal ESR index: Equality (orgId) -> Sort (priority) -> Range (createdAt)
db.events.createIndex({ orgId: 1, priority: -1, createdAt: 1 });Indexing { orgId: 1, createdAt: 1, priority: -1 } because createdAt appears in the filter before sort forces a blocking SORT stage whenever multiple createdAt values match.
How do you diagnose slow queries using explain('executionStats') in MongoDB?
Senior Engineering Answer
Running explain('executionStats') reveals the winning query plan and actual runtime counters. Key indicators include stage (IXSCAN vs COLLSCAN, or an unindexed SORT), totalKeysExamined versus totalDocsExamined relative to nReturned, and executionTimeMillis. A high ratio of totalDocsExamined to nReturned means the index lacks selectivity; zero totalDocsExamined with PROJECTION_COVERED indicates a fast covered query served entirely from the index.
db.orders.find(
{ customerId: "cust_42", status: "shipped" },
{ _id: 0, orderNumber: 1 }
).explain("executionStats");Checking only explain('queryPlanner') shows the chosen plan shape without revealing whether an index scan actually examined hundreds of thousands of keys in production.
How does MongoDB's aggregation pipeline optimize stage ordering, and what causes the 100 MB stage memory limit error?
Senior Engineering Answer
Each aggregation stage transforms a stream of documents into the next stage. To run efficiently, place $match and $sort as early as possible so MongoDB can push filters down to an index scan, and use $project early to drop large unused fields. Blocking stages like $group and unindexed $sort buffer data in memory and fail once a single stage exceeds 100 MB unless you pass allowDiskUse: true (or enable spilling to disk in newer server versions).
db.orders.aggregate([
{ $match: { status: "completed", createdAt: { $gte: ISODate("2026-01-01") } } },
{ $group: { _id: "$country", revenue: { $sum: "$total" }, count: { $sum: 1 } } },
{ $sort: { revenue: -1 } },
{ $limit: 10 }
], { allowDiskUse: true });Running $lookup or $unwind before $match forces MongoDB to join or explode every document in the collection instead of filtering the working set first.
How do TTL indexes and capped collections differ for managing time-series or expiring data?
Senior Engineering Answer
A TTL index automatically deletes documents once a Date field passes expireAfterSeconds; a background thread runs roughly every 60 seconds, making it ideal for sessions, OTPs, and retention policies where age governs deletion. A capped collection is a fixed-size circular buffer that preserves insertion order and overwrites the oldest documents automatically when full, but prohibits explicit document deletions or size-expanding updates.
// Expire session documents 3600 seconds after lastActiveAt
db.sessions.createIndex({ lastActiveAt: 1 }, { expireAfterSeconds: 3600 });Expecting TTL deletion to occur at the exact second of expiration; because the TTL monitor runs once per minute under varying load, application queries must still filter on expiresAt > now.
How does the WiredTiger storage engine handle concurrency, caching, checkpoints, and crash recovery?
Senior Engineering Answer
WiredTiger uses optimistic concurrency control (MVCC) with document-level locking, allowing concurrent writers on distinct documents without blocking readers. Dirty pages live in an in-memory WiredTiger cache (defaulting to ~50% of RAM minus 1 GB) and are flushed cleanly to disk via checkpoints every 60 seconds. To guarantee durability between checkpoints, WiredTiger writes compressed write-ahead journal records to disk using a separate journal sync interval (typically 100 ms or immediately with j: true).
// Force journal flush before returning acknowledgment
db.payments.insertOne(
{ txId: "tx_8821", amount: NumberDecimal("250.00") },
{ writeConcern: { w: "majority", j: true } }
);Disabling journaling or lowering write concern to w: 1 without considering crash recovery can silently lose acknowledged writes if a primary node loses power before the next 60-second checkpoint.
How do Write Concern, Read Concern, and Read Preference interact to ensure strong consistency in a MongoDB replica set?
Senior Engineering Answer
Write Concern (w: 'majority') waits until a quorum of voting replica set members writes the operation to their oplogs before acknowledging success, preventing rollbacks during primary failover. Read Concern controls isolation: 'local' returns the node's latest data (which could roll back), 'majority' returns only quorum-committed data, and 'linearizable' checks quorum on the primary for real-time ordering. Read Preference routes reads (primary, primaryPreferred, secondaryPreferred), where reading from secondaries trades freshness for read scaling due to replication lag.
// Strongest read-after-write consistency across failover boundaries
const doc = await db.collection("ledgers").findOne(
{ accountId: "acct_19" },
{ readConcern: { level: "majority" }, readPreference: "primary" }
);Using Read Preference 'secondaryPreferred' together with Read Concern 'local' for read-after-write workflows causes stale reads because asynchronous oplog replication lags behind the primary.
How does MongoDB replica set failover work, and what causes an election rollback?
Senior Engineering Answer
Replica set members exchange heartbeats every 2 seconds. If the primary becomes unreachable for electionTimeoutMillis (default 10 seconds), an eligible secondary with the highest oplog optime and priority initiates a Raft-inspired election and must obtain votes from a strict majority of voting members. If the former primary had accepted writes with w: 1 that were not yet replicated to the newly elected primary, it rolls back those diverging oplog entries into BSON rollback files upon rejoining.
// Typical 3-member replica set configuration check
rs.status().members.map(m => ({
name: m.name,
stateStr: m.stateStr,
optimeDate: m.optimeDate
}));Deploying an even number of voting nodes (e.g., 2 data nodes without an arbiter or 3rd member) prevents achieving a strict majority when one node goes down, leaving the cluster read-only.
How do multi-document ACID transactions work in MongoDB, and when should you avoid them?
Senior Engineering Answer
MongoDB supports snapshot-isolated multi-document transactions across replica sets and sharded clusters using WiredTiger snapshots and two-phase commit across shards. However, transactions incur higher wired-tiger cache pressure, lock contention, a default 60-second lifetime limit, and cross-shard network coordination overhead. Because single-document writes are already atomic, well-modeled schemas avoid transactions on hot paths and reserve them for infrequent multi-aggregate invariants like double-entry transfers.
const session = client.startSession();
try {
await session.withTransaction(async () => {
await accounts.updateOne({ _id: fromId }, { $inc: { balance: -100 } }, { session });
await accounts.updateOne({ _id: toId }, { $inc: { balance: 100 } }, { session });
}, { writeConcern: { w: "majority" }, readConcern: { level: "snapshot" } });
} finally {
await session.endSession();
}Forgetting to pass { session } to every CRUD call inside withTransaction causes those operations to execute outside the transaction boundary without snapshot isolation or rollback.
How do you choose an effective shard key for a high-throughput sharded MongoDB cluster, and why is a monotonically increasing key dangerous?
Senior Engineering Answer
A shard key determines how chunks (default 128 MB) are distributed across shards and how mongos routers route queries. An ideal shard key exhibits high cardinality, low frequency (no massive hot values), and aligns with common query predicates to enable targeted queries rather than scatter-gather across all shards. Using a monotonically increasing key like ObjectId or timestamp with ranged sharding directs 100% of inserts to the single rightmost chunk on one shard, creating a severe write hotspot.
// Compound shard key balances targeted tenant queries with write distribution
sh.shardCollection("analytics.events", { tenantId: 1, bucketHash: 1 });
// Alternative for uniform insert spread without range queries on _id:
sh.shardCollection("analytics.rawLogs", { _id: "hashed" });Choosing a low-cardinality shard key (such as region or status) produces indivisible jumbo chunks that cannot split, causing permanent storage imbalance across shards.
How do Change Streams operate internally on the oplog, and how do you build resilient idempotent consumers with resume tokens?
Senior Engineering Answer
Change Streams open a tailable cursor against the replica set's local.oplog.rs (or coordinated across shards by mongos), emitting cluster-wide majority-committed change events ordered by clusterTime. Each event carries an opaque _id resume token. Resilient consumers persist the last processed resume token atomically with downstream state updates and restart the cursor with resumeAfter (or startAfter if an invalidate event occurs), keeping handlers idempotent in case of at-least-once redelivery.
const stream = db.collection("orders").watch(
[{ $match: { operationType: { $in: ["insert", "update"] } } }],
{ fullDocument: "updateLookup", resumeAfter: savedToken }
);
for await (const event of stream) {
await processIdempotently(event);
await saveCheckpointToken(event._id);
}If a consumer stays offline longer than the oplog retention window, its saved resume token expires and throws ChangeStreamHistoryLost, requiring a full snapshot resync.
How do you diagnose and resolve WiredTiger cache eviction stalls and working-set thrashing under heavy load?
Senior Engineering Answer
When active indexes and hot documents exceed the WiredTiger cache size, application threads are forced to perform synchronous page eviction (tracked via cache.pages evicted by application threads and dirty fill ratio exceeding 20%). Remediation includes trimming redundant or unused indexes, shrinking document size (or splitting cold fields to an archive collection), ensuring queries use selective indexes rather than scanning cold pages, and scaling vertical RAM or sharding horizontally.
// Inspect WiredTiger cache fill and dirty pressure
const wt = db.serverStatus().wiredTiger.cache;
print({
bytesInCacheMB: Math.round(wt["bytes currently in the cache"] / 1048576),
dirtyMB: Math.round(wt["tracked dirty bytes in the cache"] / 1048576),
appEvictions: wt["pages evicted by application threads"]
});Adding speculative indexes to speed up secondary queries increases index footprint in the WiredTiger cache, often worsening overall eviction stalls for primary workloads.
How do you architect zero-downtime shard key refinements and live cluster migrations in MongoDB?
Senior Engineering Answer
MongoDB supports reshardCollection (v5.0+) and refineCollectionShardKey (v4.4+). refineCollectionShardKey adds suffix fields to an existing shard key instantaneously as a metadata operation to fix jumbo chunks without moving data. When changing the prefix or hashing strategy completely, reshardCollection clones data to new shard topologies in the background while tailing the oplog, then briefly acquires a brief critical-section write pause (seconds) to cut over.
// Non-disruptive suffix refinement to split jumbo chunks
db.adminCommand({
refineCollectionShardKey: "saas.invoices",
key: { orgId: 1, invoiceMonth: 1, _id: 1 }
});Attempting reshardCollection without verifying sufficient free disk headroom (roughly 1.2x collection size) and stable oplog window across shards can abort the cutover mid-clone.
MongoDB Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis MongoDB preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Databases & Storage.
How does MongoDB store data as BSON documents, and what practical limits does BSON impose compared to JSON?
What is the difference between findOneAndUpdate, updateOne, and replaceOne in MongoDB?
When should you model relationships in MongoDB using embedded subdocuments versus normalized document references?
How do single-field, compound, and multikey indexes work in MongoDB, and what happens when indexing array fields?
How do you apply the Equality, Sort, Range (ESR) rule when designing compound indexes?
How do you diagnose slow queries using explain('executionStats') in MongoDB?
Frequently Asked Technical Interview Questions (MongoDB)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
When is MongoDB a stronger architectural fit than PostgreSQL, and vice versa?
What is the purpose of the MongoDB oplog, and how should its size be tuned?
How does MongoDB handle connection pooling in serverless or high-concurrency backends?
What is the Bucket Pattern in MongoDB and when should you use it?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.