MongoDB Interview Questions and Answers for 2026

MongoDB interview questions show up in a large share of backend, data, and platform hiring loops, because a serious fraction of production databases are document stores. This page is a complete, tiered bank: 104 questions with worked answers, split into beginner, intermediate, and scenario sections, plus hands-on labs, a command cheat sheet, and a five-question quiz at the end. Work through it in order, or jump straight to the tier that matches your next interview round.

MongoDB interview questions tiered bank covering documents, indexes, replication, sharding, and troubleshooting
The three tiers in this bank: foundations, working mechanics, and production incidents under pressure.

TL;DR

  • 104 questions, three tiers. Beginner document and CRUD fluency, intermediate index and replication mechanics, and realistic incident rounds, each with a worked answer in the shape interviewers grade.
  • Mechanism first. Every answer names the component that owns the behavior, from the WiredTiger cache to the balancer, then the command, then the operational caveat that separates a pass from a strong hire.
  • Practice is built in. Three scenario labs, a cheat sheet of the commands that come up most in MongoDB interview questions, and a five-question quiz to check what stuck.

How the MongoDB interview works in 2026

Most MongoDB interview questions arrive in one of three rounds. The first is a screening call that mixes definitions with quick checks: documents versus tables, what BSON adds over JSON, how _id works, what a collection scan means. These are confidence filters. Nobody wants a lecture; they want a crisp 30-second answer with one level of detail behind it, delivered without hesitation.

The second round is the deep technical, and this is where MongoDB interview questions get mechanical: compound index design and the ESR ordering, explain plans read as stage chains and counters, WiredTiger cache behavior, oplog mechanics, elections, write and read concerns, shard key properties, chunk migrations, transaction semantics. Interviewers at this stage are listening for whether your knowledge has edges. Saying indexes make queries fast passes a beginner bar; explaining why docsExamined dwarfs nReturned and exactly what you would add to the index passes a working-engineer bar. Most MongoDB interview questions are graded on that second sentence, not the first.

The third round is the scenario round: one symptom sentence, then silence while you think out loud. This aggregation times out in prod. Reads are stale after failover. Every insert lands on one shard. What gets scored is your diagnostic order, not your luck. Engineers who say first I check the plan, then the counters, then the cache stats, because X outperform engineers who guess at flags. Most scenario MongoDB interview questions are lost on method, not knowledge.

Role shape moves the emphasis. Backend roles weight MongoDB interview questions toward schema design, aggregation, and transactions, because that is where application correctness lives. Data roles push pipeline mechanics and modeling hard. DevOps and platform roles care about replica sets, sharding, backups, monitoring, and the failure modes of each: lag, elections, rebalancing, restore drills. The base bank on this page is the same; only the depth expectation moves.

Preparation that works is boringly mechanical: a throwaway cluster in Docker, this bank spoken aloud one answer at a time, and deliberate breakage. Query a big collection without an index and watch the plan change, kill a primary and watch the election, insert against a monotonic shard key and watch the hotspot appear. Rehearse the scenario tier like a demo, because a live scenario round is a demo. Treat MongoDB interview questions as a performance backed by evidence, and the rounds stop being surprises.

Core concepts interviewers expect you to know

Three mental models unlock most MongoDB interview questions: what the document model actually buys and costs, how the query engine decides between an index and a scan, and how replication and sharding split the reliability and scale story. If you can narrate all three fluently, most follow-ups become extensions rather than new topics, and that is exactly why interviewers open MongoDB interview questions here.

Documents, BSON, and the flexible schema

A MongoDB document is a set of field-and-value pairs, nested to arbitrary depth, arrays allowed, capped at 16 MB. BSON is the binary encoding under the JSON look, and its extra types carry real weight: ObjectId for identifiers, Date for timestamps that sort correctly, int64 and Decimal128 for exact numbers, binary for UUIDs. Collections hold documents the way tables hold rows, but without a forced schema: two documents in one collection can carry different fields. That flexibility is a tool with a price, and the mature position in MongoDB interview questions is to manage it: schema validation with $jsonSchema on writes, disciplined field naming, and modeling choices that match access patterns instead of fighting them after launch.

The modeling conversation underneath is embedding versus referencing. Embedded data is fetched in one round trip and updated atomically inside its document, which is why the core advice reads: data accessed together lives together. References keep documents small and avoid duplication, at the cost of extra reads and $lookup joins. The bounded-growth test decides most cases: a bounded array like an order’s line items embeds well, an unbounded one like comments on a viral post must reference out or bucket into fixed-size groups. A 16 MB limit meeting an array that doubles every release is the classic war story behind schema design questions, and you can retell it in your own words.

Indexes, explain plans, and the query engine

Indexes are B-trees: sorted structures the engine walks instead of scanning the collection. The single-field case is easy; the interview case is the compound index, governed by the ESR rule: Equality fields first, Sort fields next, Range fields last, with the prefix rule deciding which queries can use which index. A covered query, where filter, sort, and projection all live in one index, is the fastest read path and shows up in explain as an index scan with no FETCH stage at all. The tax side is real: every insert and update touches every index on the collection, so dead indexes are live write latency, which is why usage auditing appears in operational MongoDB interview questions.

explain() is how you prove any of this. Run with executionStats verbosity, it returns the stage chain, COLLSCAN versus IXSCAN versus FETCH versus a blocking SORT, plus the counters that grade the plan: keysExamined, docsExamined, nReturned, and executionTimeMillis. Senior engineers read the ratios more than the milliseconds, because milliseconds move with load and cache state while ratios expose the plan itself: a strong plan returns one document per few examined keys, a weak one drags half the collection for a handful of hits. That habit of reading plans instead of guessing is precisely what the mechanical tier of MongoDB interview questions is built to test.

Query filter, sort, project Query planner picks and caches a plan IXSCAN keysExamined COLLSCAN every document read FETCH docsExamined Results nReturned then Healthy plans: nReturned close to keysExamined and docsExamined. A COLLSCAN on a hot path is a finding.
The planner chooses a cached plan: an index walk that fetches few documents, or a collection scan that reads all of them.

Replica sets, sharding, and how they split the story

Replication is the reliability half. A replica set is one primary plus secondaries: the primary records every write in a capped oplog, secondaries pull and apply it asynchronously, and a Raft-derived election promotes a new primary in roughly ten seconds when the old one times out, always requiring a majority. Write concern controls how many members must hold a write before the driver gets its ack, read preference controls where reads run, and read concern controls how committed those reads must be. Lag, elections, and rollback all fall out of this one architecture, which is why reliability-themed MongoDB interview questions almost always reduce to it.

Sharding is the scale half. A sharded cluster splits collections across shards, each shard itself a replica set, with mongos routers in front and config servers holding the metadata. The shard key decides everything: which shard holds which range, whether a query targets one shard or scatters across all of them, and whether inserts spread evenly or hot-spot onto one machine. Chunks, the key ranges that migrate between shards, are the balancer’s currency. Underneath it all sits the WiredTiger engine with its cache, MVCC snapshots, checkpoints, and journal, and that full stack is where every scenario in this bank lives.

Driver writes to primary Primary accepts all writes Secondary 1 applies oplog Secondary 2 applies oplog Primary lost: members elect a new primary, majority required oplog, async oplog, async A replica set in one picture
Writes land on one primary, replicate asynchronously through the oplog, and elections restore a primary from majority votes.

Notice how the models compose. The document model decides what one atomic write covers, the index model decides what one read costs, and the replication and sharding models decide how both behave as data and traffic grow. Interviewers sequence follow-ups along exactly that spine: definition, then mechanism, then failure mode. Keep the spine in mind and the bank below reads as one subject instead of 104 disconnected items.

Question bank at a glance

The bank below is organized the way MongoDB interview questions are actually asked: broadly increasing difficulty, then the scenario round that finishes most loops. Counts are exact, so you can pace a week of prep: roughly 15 beginner questions a day gets you through the bank in a working week, with the labs on the weekend.

SectionQuestionsWhat it proves
Beginner38You use MongoDB daily and know documents, CRUD, and core vocabulary cold.
Intermediate40You understand mechanisms: indexes and explain plans, WiredTiger, replication, sharding, transactions.
Scenario and troubleshooting26You can diagnose a production incident in a defensible order.

Difficulty inside each tier still rises as you go, so if a section starts feeling easy near its end, that is the signal to move on. Every answer includes the mechanism plus the command or consequence, because MongoDB interview questions are graded on both halves: the right tool, and the right explanation of why that tool applies.

Beginner MongoDB interview questions

These 38 open the way most MongoDB interview questions open: vocabulary, CRUD, and the document model. They look easy, and that is the trap, because interviewers use them to check precision. Answer each in one or two sentences, then add exactly one supporting detail. More than that burns round time; less sounds like a memorized list.

What is MongoDB, in one sentence?

Answer: A distributed document database: it stores JSON-shaped documents, actually BSON, in collections instead of rows in tables, with a flexible per-document schema, rich indexing, and built-in replication and sharding. The sentence to land cleanly: documents, not rows; fields can vary per document; horizontal scaling is a native feature, not a bolt-on. That combination predicts everything else, which is why follow-up MongoDB interview questions immediately probe when the flexibility helps and when it hurts.

What is a document, and what is BSON?

Answer: The unit of data: field-and-value pairs, nested, arrays allowed, 16 MB maximum. BSON is the binary encoding MongoDB stores and sends: JSON’s shape plus real types like ObjectId, Date, int32, int64, Decimal128, and binary. The practical point is type fidelity: money uses Decimal128 because doubles round, timestamps are true dates so range queries order correctly, and drivers map it all to native types. This is among the most common MongoDB interview questions because every other topic builds on it.

How is a collection different from a table?

Answer: A collection groups documents the way a table groups rows, but no schema is enforced across it by default: two documents can carry different fields. There are no enforced joins either; related data is embedded or combined with $lookup. Since 3.2 you can attach optional schema validation, and disciplined teams do, because unmanaged flexibility is a liability, not a feature. That nuance is exactly what beginner MongoDB interview questions on this topic listen for.

What is the _id field?

Answer: Every document carries an immutable _id that acts as the primary key and is automatically backed by a unique index in every collection. If you omit it, the driver generates an ObjectId. Consequences worth stating: values are unique per collection, any BSON type works except an array or regex, and it can never be updated after insert. The default ObjectId starts with a timestamp, so sorting by _id approximates insertion order, but it is second-resolution and not a substitute for a real createdAt field.

What is an ObjectId made of?

Answer: 12 bytes: a 4-byte Unix timestamp of creation, 5 bytes of per-process random value, and a 3-byte incrementing counter. Sorting by _id gives cheap approximate time ordering, which people exploit for cursors, but the timestamp has one-second resolution, so it is not a precise clock. You can extract the creation time with ObjectId.getTimestamp(). Knowing the byte layout plus the ordering caveat is the complete expected answer.

How do you insert documents?

Answer: insertOne for a single document, insertMany for batches, which make one round trip and vastly outperform looping single inserts. By default insertMany is ordered and stops at the first error; ordered: false keeps going and reports per-document failures. Both return the generated _id values so callers can reference what landed. Bulk loading belongs in batches, and knowing the ordered flag is the detail that separates this entry from recital-level answers.

How does find() work, and what does a basic query look like?

Answer: db.users.find({ status: "active", age: { $gt: 30 } }) returns a cursor over matching documents: the first argument is the filter, the optional second is the projection. An empty filter means the whole collection. The habit to demonstrate while answering: think immediately about which fields the filter touches, because that decides whether an index can serve it or a collection scan will. Queries are documents too, so the shape of the filter is data, not magic, and the find form is the front door of MongoDB interview questions, so keep it automatic.

What are the common comparison operators?

Answer: $eq, $ne, $gt, $gte, $lt, $lte, plus $in for a value list and $nin for its inverse, as in db.orders.find({ status: { $in: ["paid", "shipped"] } }). One caveat that earns credit: $ne and $nin often use indexes poorly and can degrade toward wide scans, so prefer positive matches when the model allows. Operator fluency at the shell is the entry ticket to the rest of this bank.

What do $and, $or, $not, and $nor do?

Answer: Multiple fields in one filter document form an implicit $and. You need explicit forms for alternatives: db.users.find({ $or: [{ status: "active" }, { age: { $lt: 18 } }] }), with $not negating an operator expression and $nor rejecting everything matched. The case that forces explicit $and: the same field appearing twice, like a range written as two conditions on one key. Knowing when the explicit form is mandatory is the graded half of this question.

How do you query fields inside embedded documents?

Answer: Dot notation: db.users.find({ "address.city": "Berlin" }), which reaches embedded subdocuments and array elements alike. You can also match a whole subdocument exactly, but that requires every field in the exact order stored, so dot notation is the practical choice. The same syntax indexes cleanly, and quoted keys are required in most drivers because the dot must reach MongoDB literally. Dot notation fluency is assumed by every later question, so make it a reflex.

How do you query arrays?

Answer: Three distinct matches: an exact match requires the entire array including order; a bare condition like { tags: "red" } matches documents where any element equals red; and $elemMatch requires one single element to satisfy multiple conditions, as in { scores: { $elemMatch: { $gte: 80, $lt: 90 } } }. Without $elemMatch, two conditions can be satisfied by two different elements, which is the classic trap interviewers set here. Naming the trap is the whole answer.

What is projection in find()?

Answer: The second argument limits returned fields: { name: 1, email: 1 } includes those plus _id, while exclusions like { password_hash: 0 } return everything else. Beyond trimming payload, projection ties into performance: if one index holds every projected field, MongoDB can answer entirely from the index without touching documents, a covered query. That bridge from a beginner flag to a performance mechanism is why projection recurs in MongoDB interview questions.

What do sort, skip, and limit do?

Answer: Cursor methods chained after find: .sort({ created_at: -1 }).skip(20).limit(10), the shape behind every pagination call. MongoDB can satisfy sorts from an index order; without one it performs a blocking in-memory sort with a memory cap, and large sorts need allowDiskUse or an index. Deep skip values get expensive because the server walks and discards, so real pagination at scale prefers range cursors on a stable sort key. Saying that last part converts this from syntax into judgment, and pagination behavior is a small topic MongoDB interview questions use to find people who have shipped.

What is a cursor?

Answer: find does not return documents; it returns a cursor the driver iterates in batches, first batch typically 101 documents or under, then more on demand via getMore. The server-side cursor expires after about 10 minutes idle by default, so long pauses mid-iteration lose it. Practical consequences worth naming: batchSize controls memory per round trip, cursors are closed explicitly or on exhaustion, and sort, limit, and skip are cursor-level operations. Understanding batching explains a surprising number of memory and timeout mysteries.

How do you count documents, and what is the catch?

Answer: countDocuments(filter) runs an aggregation that counts precisely, using indexes when the filter allows; estimatedDocumentCount() reads collection metadata and is near-instant but ignores filters and drifts slightly. The legacy db.collection.count() wrapper hides the difference, which is the real reason the question exists. Filtered counts on big collections should always be the precise form, a constantly counting dashboard belongs in a summary document updated incrementally rather than scanned per page load, and counting correctly is a small credibility test inside many MongoDB interview questions.

What is the difference between embedded documents and references?

Answer: Embedding stores related data inside the parent document; referencing stores an _id pointer and fetches on demand, joined in application code or with $lookup. Embedding reads in one round trip and updates atomically within the document; referencing keeps documents small and avoids duplication at the cost of extra queries. The rule of thumb that answers most design-flavored MongoDB interview questions: data accessed together and bounded in size embeds, everything else references.

When is embedding the right choice?

Answer: One-to-few relationships that are always read together: an order with its line items, a device with its configuration. Run the three tests: does the child data exist only in this parent’s context, is its growth bounded, and is it fetched whenever the parent is. Embedding also buys atomicity, since updating parent and children together is one atomic document write. Unbounded growth, like comments on a popular post, fails the tests and must reference or bucket instead, which is the follow-up most MongoDB interview questions take.

Which BSON types matter day to day?

Answer: String, Boolean, Date, null, int32, int64, double, Decimal128, Object, Array, ObjectId, and binary for UUIDs. Two earn explicit mention: Decimal128 for money, because binary doubles accumulate rounding error, and true Date values rather than epoch integers in strings, so ranges and sorts behave. One systems detail worth a sentence: MongoDB compares values across types by BSON type ordering, so a field holding mixed types produces surprising sort results. Type discipline prevents a whole class of bugs interviewers love to describe.

What is a capped collection?

Answer: A fixed-size ring buffer: inserts append, oldest documents are evicted automatically when the size or count cap is hit, and document deletion or growth is not allowed. Create one with db.createCollection("events", { capped: true, size: 100000 }). Typical uses are log tails, oplogs, and small job queues, and tailable cursors can follow new inserts, which is how tail-style consumers work on them. The engine’s own oplog being capped is the best example to cite, because it explains why oplog window matters for replication.

What are indexes, at a beginner level?

Answer: Sorted B-tree structures that let the engine find matching documents without scanning the collection, like a book index instead of reading pages. Every collection gets one on _id automatically; you add more with db.users.createIndex({ email: 1 }). The cost side completes the answer: each index slows every write and consumes RAM and disk, so indexes are chosen, not sprinkled. Interviews grade both halves, the acceleration and the tax, because production behavior lives in the balance between them, and this tradeoff is the foundation on which performance MongoDB interview questions are built.

How do you create, list, and remove indexes?

Answer: createIndex({ field: 1 }) builds one, ascending or descending per field; getIndexes() lists them with auto-generated names like field_1; dropIndex("field_1") removes one, and dropIndexes() clears all except _id. Builds in modern versions are online: reads and writes continue while the collection is scanned, at the price of background load. Mention unique or TTL options exist at creation and you have covered the beginner surface; the mechanics come later in the bank.

Can you drop the _id index?

Answer: No. It is the primary key index: unique, required, immutable, and not droppable. When a natural key needs uniqueness, like a username or an external ID, the correct move is an additional unique index on that field, not attempts to repurpose _id. A related trap worth naming: generating your own _id values is fine and common, but they must be unique per collection or the insert fails with a duplicate key error. This question checks whether you know which rules in MongoDB are load-bearing.

What does explain() tell you?

Answer: Append .explain() to a query and MongoDB describes the plan: a COLLSCAN stage means a full collection scan, IXSCAN means an index walk, FETCH pulls full documents after the index hit, and a SORT stage means it had to sort in memory. The queryPlanner mode shows the chosen plan; executionStats adds the counters: keysExamined, docsExamined, nReturned. The reflex being tested: run explain before guessing why anything is slow. This one command opens most performance-flavored MongoDB interview questions.

What is mongosh?

Answer: The modern MongoDB Shell, successor to the legacy mongo client: a JavaScript environment where the database is a first-class object, so db.users.find() is literally code. It handles CRUD, administration, and scripted automation, since mongosh script.js runs files for maintenance jobs. Shell syntax tracks driver syntax closely, which makes it the fastest way to explore and rehearse. For this tier of MongoDB interview questions, knowing it exists, what replaced it, and that it doubles as a scripting tool is the full expected depth.

How do you import and export data?

Answer: mongoimport and mongoexport move JSON and CSV in and out, ideal for handoffs and dataset seeding. mongodump and mongorestore move BSON, preserving types exactly, and serve as the quick backup pair, though not the production-grade one. The line worth drawing out loud: exports are for interchange, dumps are for recovery, and real production backups use storage snapshots or continuous backup tooling for point-in-time restore. Choosing between them by use case is what the question actually grades.

What is the aggregation pipeline, in one sentence?

Answer: A data processing conveyor: documents flow through stages in order, and each stage transforms them, like $match filtering, $group aggregating, $sort ordering, $project reshaping. It fills the role SQL fills with SELECT plus GROUP BY, composed explicitly stage by stage instead of in one declarative statement. The one detail worth adding to the sentence: stage order is performance, because filtering early shrinks the work of every later stage. Depth on stages and memory limits comes in the next tier.

Why does $match belong early in a pipeline?

Answer: Every stage hands its entire output to the next, so filtering first means $group and $sort chew on fewer documents. An early $match whose filter matches an indexed field can also use that index and skip whole ranges of input, which a late one cannot, because by then the documents no longer look like the collection. The optimizer does move some stages, but designing as if it will not is the professional habit. This single rule fixes more slow pipelines than any server flag.

What is a replica set?

Answer: A group of mongod processes holding the same data: one primary accepts all writes, secondaries replicate its oplog asynchronously, and if the primary fails the survivors elect a replacement automatically. Production minimum is three voting members so a majority survives one failure. Reads can spread to secondaries through read preferences, trading freshness for capacity. Nearly every reliability-themed MongoDB interview question reduces to this structure, the definition has to be effortless, and replica set fluency is table stakes in MongoDB interview questions for any role that touches production.

What is sharding, in one sentence?

Answer: Horizontal partitioning: MongoDB splits a large collection across multiple shards, each shard a replica set, using a shard key, and mongos routers send each query to the shards that hold the data. It exists because one machine eventually hits disk, RAM, or write ceilings that many machines behind a router do not. The price is that every access pattern now depends on shard key choice, one of the highest-stakes decisions in the system. That price is exactly why the intermediate tier of this bank spends several questions there.

What is mongod and what is mongos?

Answer: mongod is the database server daemon: the process holding data, indexes, and the WiredTiger storage engine, whether standalone or as a replica set member. mongos is the stateless query router of a sharded cluster: it receives operations, consults config server metadata, and routes each one to the shards that own the key range. Clients talk to mongod directly in replica sets and to mongos in clusters. Knowing which process holds data and which only routes is the entire distinction being tested.

How do you see what exists on a server?

Answer: db prints the current database, show dbs lists databases with sizes, show collections lists the current database’s collections, and db.getCollectionNames() is the scriptable form. For sizes and counts, db.stats() and db.collection.stats() expose storage, index sizes, and document counts, which matters before migrations. The scriptable forms matter because maintenance scripts should never parse human output. Small question, but it appears in nearly every warm-up round of MongoDB interview questions.

What is a view in MongoDB?

Answer: A read-only named aggregation: db.createView("active_users", "users", [{ $match: { status: "active" } }]) stores the pipeline and re-runs it on every query against the view. Views keep reporting logic in the database and expose filtered or reshaped surfaces without duplicating data. Limits worth stating: no writes, no indexes of their own, performance inherits the underlying pipeline. They pair naturally with the aggregation tier of this bank and earn bonus points when offered unprompted.

What is schema validation?

Answer: Optional collection-level rules, usually a $jsonSchema document in the collection’s validator, that reject or warn on documents missing required fields, carrying wrong types, or out of range. validationLevel decides whether rules apply to all writes or only new ones, and validationAction chooses hard error versus warn-only. The mature framing: schemaless is a debt teams repay painfully; validation gives flexible documents guardrails. Volunteering that framing is what lands this answer in real MongoDB interview questions.

How is MongoDB different from MySQL?

Answer: Three differences carry the answer. Data model: flexible documents versus rows bound to a fixed schema, so attributes vary per record without migrations. Scaling: native replica sets and sharding versus a tradition of vertical scaling and external sharding tools. Query model: embedded data and pipelines versus joins across normalized tables. Interviewers want tradeoffs, not a winner: heavily relational, multi-entity consistency workloads often still belong in SQL, and saying so reads as maturity rather than disloyalty. Database comparisons often close MongoDB interview questions, so end on tradeoffs, not verdicts.

What is the difference between updateOne and replaceOne?

Answer: updateOne applies operators to fields of the matched document, like { $set: { status: "paid" } }, leaving every other field untouched. replaceOne swaps the whole document for the replacement, silently dropping any field you did not include; only _id survives. The bug this question hunts is real: shipping a replace where an update was meant erases data quietly. The matchedCount and modifiedCount fields in the result tell you which one actually did what.

How do $set, $inc, and $push work?

Answer: $set creates or updates a field, $inc adjusts numbers atomically on the server so concurrent writers cannot clobber each other, $push appends to an array, $addToSet adds only when absent, and $pull removes matching elements. All execute atomically within the single document, which is why counters and lightweight queues live safely inside documents without application-level locking. Naming that atomicity is the detail separating this answer from a list recital, and it feeds directly into the transactions topic later in the bank.

What is an upsert?

Answer: updateOne, updateMany, and replaceOne accept upsert: true: if nothing matches the filter, MongoDB inserts a new document built from the filter’s equality conditions plus the update. That collapses get-or-create logic into one atomic call, a standard pattern for counters, sessions, and per-user records. The classic failure is racing upserts on a non-unique key and collecting duplicates; the fix is a unique index on the filter fields so the second insert fails and retries cleanly.

How do you delete data safely?

Answer: deleteOne and deleteMany remove matching documents; deleteMany({}) empties the collection but keeps the collection, its indexes, and permissions; drop() removes the collection itself, indexes included, in one fast operation. The production habit that answers most scenario MongoDB interview questions downstream: count with the exact filter first, delete with the same filter, verify after, and never run delete-by-filter from an ad hoc session on a shared cluster. The distinction between emptying and dropping matters because nobody restores dropped indexes quickly.

Intermediate MongoDB interview questions

This tier is where MongoDB interview questions stop testing vocabulary and start testing mechanism. Forty questions follow, and the pattern to internalize is component, then command, then caveat: name the part of the system that owns the behavior, give the command that observes or changes it, and close with the operational caveat that proves you have run it in production. Build that three-beat habit here and the scenario tier becomes dramatically easier.

How does WiredTiger store data on disk?

Answer: WiredTiger, the default storage engine since 3.2, keeps each collection and index in its own B-tree, writes through MVCC snapshots rather than updating in place, and compresses data and indexes on disk (snappy by default, zstd and zlib available). Durability is checkpoints plus a write-ahead journal: checkpoints mark consistent on-disk state roughly every minute, and the journal replays everything since the last checkpoint after a crash. The key framing: crash recovery, cache, and compression belong to the engine, not the query layer. Interviewers probe that separation constantly in MongoDB interview questions about storage.

How is the WiredTiger cache sized, and what lives in it?

Answer: By default half of RAM minus one gigabyte, or 256 MB, whichever is larger; override with wiredTigerCacheSizeGB. The cache holds recently touched pages for collections and indexes, and unlike engines you may know from folklore, dirty pages flush continuously rather than piling up. The rest of RAM is not wasted: the filesystem cache holds compressed pages. The sizing rule worth saying: cache plus OS cache should comfortably hold the hot working set, because once it does not, evictions and page faults become the latency story. That rule anchors the capacity half of MongoDB interview questions.

What is MVCC in MongoDB?

Answer: Multi-version concurrency control: every operation reads a consistent point-in-time snapshot, and writers create new versions of documents instead of mutating them in place, so readers never block writers and writers never block readers. Conflicts surface as WriteConflict errors, most commonly when two transactions or concurrent updates touch the same document, and the correct response is retry, not panic. Isolation is document-level and optimistic: no lock table to inspect, just version checks. Naming the retry expectation is what makes this answer sound operational rather than academic, and expect follow-up MongoDB interview questions about retry logic, because this error is where they begin.

What is the ESR rule for compound indexes?

Answer: Equality first, Sort second, Range third. Fields filtered with equality go at the front of the index, then the fields that carry the sort so the index order satisfies it directly, then range predicates last, since a range boundary ends useful ordering for later fields. An index on { user_id: 1, status: 1, created_at: -1 } serves equality on user_id and status plus a created_at sort; putting the range before the sort kills the sort avoidance. ESR is the single most frequently asked index design question in MongoDB interview questions, so deliver it with a worked example.

Which queries can actually use a compound index?

Answer: Any query filtered on a prefix of its fields. An index on { a: 1, b: 1, c: 1 } supports filters on a, a plus b, and a plus b plus c, and sorts matching that order; a query on b alone walks it uselessly. Direction matters only for multi-field sorts; equality on a single key ignores it. Sorts can also work when equality fixes the leading fields and the sort matches the remainder. The prefix rule decides most real index designs, and prefix fluency is the dividing line most intermediate MongoDB interview questions draw.

What is a covered query?

Answer: One answered entirely inside an index: every filtered field, every sorted field, and every projected field exists in one index, so explain shows IXSCAN with totalDocsExamined: 0 and no FETCH stage. It is the fastest read path MongoDB offers and the reason projection choices matter for performance, not just payload size. The tradeoff: building a wide index to cover one hot query taxes every write, so coverage is reserved for paths with real traffic. Offer an example query and index and this answer closes itself.

What is a multikey index?

Answer: The index form MongoDB builds automatically when a field is an array: one index entry per array element, so { tags: 1 } lets { tags: "red" } hit directly. Two rules carry the question: a compound multikey index may include at most one array field, and multikey bounds over overlapping conditions behave best with $elemMatch, which pins conditions to a single element. Explain output flags multikey plans explicitly. Array-heavy documents make this topic unavoidable, the one-array-per-compound-index rule is the detail interviewers wait to hear, and array modeling is a quiet favorite in MongoDB interview questions for exactly that reason.

What are text indexes, and what are their limits?

Answer: A special index enabling $text search: it tokenizes and stems strings by language, supports per-field weights, and can compound with other fields. Limits are why senior answers hedge: one text index per collection, larger and slower to build than B-trees, basic phrase and relevance behavior. At production scale the honest recommendation is a dedicated search system, Atlas Search or an external engine, fed by change streams, with text indexes as the built-in stopgap. Giving the honest comparison rather than a feature list is what this entry grades, and it shows how MongoDB interview questions test honesty over feature recall.

How do TTL indexes work?

Answer: A single-field index created with expireAfterSeconds: a background TTL monitor runs about every 60 seconds and removes documents whose indexed date field is older than the expiry. The field must hold BSON dates, and arrays of dates use the earliest element. Consequences worth stating out loud: expiry is asynchronous and load-sensitive, so it is a cleanup mechanism, not a scheduler; deletion pressure on huge expiring collections shows up as write load; and changing the expiry later means a rebuild or collMod on newer versions. Sessions, tokens, and logs are the canonical uses, and TTL mechanics anchor a whole family of MongoDB interview questions about lifecycle data.

What are partial indexes?

Answer: Indexes over a subset of documents, defined by a partialFilterExpression such as { status: "active" } or a field-existence check. They are smaller, faster to search, and cheaper to maintain on writes than full indexes. The catch that makes the question: a query only uses the partial index when its predicate is provably compatible with the filter expression, and the planner silently skips it otherwise, which explain will reveal. Partial indexes cover most legacy sparse-index use cases with better predictability, and offering that comparison reads as experience.

What do sparse and unique indexes do, and how do they combine?

Answer: Sparse indexes omit documents lacking the indexed field entirely; unique indexes enforce value uniqueness across the documents where the field exists, with null counting as a value. The classic combo is sparse plus unique for an optional-but-unique field like a secondary email, so absence is allowed and presence is exclusive. Uniqueness can span compound keys and is collation-sensitive, so case handling is a design decision. The E11000 duplicate key error is the signature you will meet in production logs, recognizing it instantly is the practical half of this answer, and optional-but-unique fields recur in MongoDB interview questions more than any other index option.

What are wildcard indexes?

Answer: Indexes declared as { "$**": 1 } or scoped like { "attributes.$**": 1 } that automatically index every field under a path, built for polymorphic documents whose queryable fields are unpredictable, event payloads and product attributes being the textbook cases. The planner can use them for arbitrary equality queries on fields inside the path. Caveats to volunteer: they are not a modeling strategy, known hot fields still deserve real compound indexes, and they carry the same write tax as any index across a wider surface. Schema chaos is a modeling smell, not an indexing opportunity, and saying so scores.

What do COLLSCAN, IXSCAN, FETCH, and SORT stages mean in explain output?

Answer: COLLSCAN walks the entire collection; IXSCAN walks an index; FETCH retrieves full documents by record id after the index hit; SORT is a blocking in-memory sort. Read the chain bottom-up: IXSCAN with no FETCH signals a covered query, IXSCAN with docsExamined far above nReturned signals weak selectivity, and a COLLSCAN anywhere on a hot path is a finding, not a style choice. Stage vocabulary is the shared language of every performance conversation, which is why this question appears in nearly every intermediate MongoDB interview round.

What are the explain verbosity modes, and when is each safe?

Answer: queryPlanner reports the chosen and rejected plans without executing, safe anywhere; executionStats actually runs the query and reports keysExamined, docsExamined, nReturned, and timing, so it belongs on staging or a light production query; allPlansExecution additionally exercises the rejected candidate plans, costing the most. The discipline being tested: never run the heavy modes against a heavy production query casually, because explain executes what you hand it. Verbose modes on the slow path, planner-only on the hot path, is the rule.

How do you read keysExamined, docsExamined, and nReturned?

Answer: keysExamined is index entries walked, docsExamined is documents fetched or scanned, nReturned is what came back. The ideal plan has all three close together; docsExamined far above nReturned means the plan drags documents it discards, usually weak selectivity or a missing index field; keysExamined far above nReturned means a deep range walk with few hits. Ratios beat milliseconds in these MongoDB interview questions because milliseconds move with cache warmth and load, while ratios describe the plan itself, which is stable.

What is $indexStats for?

Answer: An aggregation stage reporting per-index usage since server start: access counts and the operations that caused them. It is how dead indexes get found: an index nobody can explain, with near-zero accesses across a full business cycle, is pure write tax and cache waste. The professional loop: collect stats over a representative period, confirm with the owning team, drop during a quiet window, and keep the profiler watching for regressions. Index hygiene is an ongoing duty, and this stage plus getIndexes is the whole toolkit for it.

How does the aggregation pipeline handle memory?

Answer: Streaming stages like $match and $limit flow documents through; blocking stages like $group, $sort, and $bucket accumulate state in memory with a 100 MB per-stage limit, erroring past it unless allowDiskUse lets them spill to temporary files at a speed cost. Design discipline stays cheaper than spill: filter early, group on selective keys, and sort only what survives. Heavy reporting belongs on a secondary or a warehouse, not the primary during business hours. The 100 MB number is the expected detail in this family of MongoDB interview questions.

Collection 1M documents $match index-backed $group 100 MB limit $sort few docs left Results $project, $limit Filter early: every later stage shrinks, sorts stay in memory Aggregation as a conveyor each stage hands its full output to the next
Stage order is performance: an index-backed $match up front keeps $group and $sort under their memory limits.
What do $lookup and $graphLookup do, and what do they cost?

Answer: $lookup joins each input document against a foreign collection by equality on two fields or by an arbitrary sub-pipeline, behaving like a left outer join; $graphLookup walks recursive relationships such as org charts and bill-of-materials trees to a fixed depth. Cost control is the graded part: index the foreign join field or every left-side document scans the right side, filter before joining, and expect fan-out to multiply documents through later stages. Heavy $lookup per request is usually a modeling smell, and saying that is the senior move.

What are $facet and $bucket used for?

Answer: $facet runs several sub-pipelines over the same input in one pass, the canonical case being a page of results plus the total count plus category breakdowns together, saving three round trips. $bucket and $bucketAuto segment documents into value ranges, histogram style, with $bucketAuto choosing boundaries for you. Both inherit the memory limits of their inner stages, so a facet containing a huge $sort is still a blocking sort. They are reporting workhorses, and the caveat about inherited memory is the detail that elevates the answer.

What are change streams?

Answer: A supported API over the oplog: applications watch insert, update, delete, and DDL events at collection, database, or deployment scope and receive events with resume tokens for restart-from-where-you-left. They need a replica set, since standalone servers have no oplog, and majority read concern support underpins the resume guarantees. Use cases worth naming: cache invalidation, syncing a search index, feeding analytics, and triggering workflows. Interviewers specifically like hearing resume tokens and the full-document lookup option, because both show you have shipped something on change streams rather than read about them.

How does the oplog work?

Answer: The oplog, local.oplog.rs, is a capped collection recording every write as an idempotent operation; secondaries pull from it and apply changes in order, parallelizing where document boundaries allow. It is also the substrate for change streams, initial sync, and point-in-time restore replay. The operational fact that matters most: it is a rolling window, so a secondary falling behind past the oldest entry becomes stale and needs a full resync. Sizing the oplog to outlast your longest maintenance window is the senior detail in this answer.

How does a replica set election work?

Answer: Replica sets run a Raft-derived protocol: members exchange heartbeats, and when the primary is unreachable past the election timeout, default ten seconds, eligible members campaign and a majority must agree before anyone becomes primary. Member priority biases the outcome, and a member that cannot see the majority steps down even if healthy, which is how network partitions are survived safely. Odd voting member counts matter because majorities are the safety property. Expect follow-ups about priority zero members and hidden members, know both are non-voting or invisible by configuration, and keep the majority rule handy because election mechanics decide several scenario MongoDB interview questions downstream.

What do write concerns w:1, w:majority, and j:true mean?

Answer: w: 1 acknowledges when the primary holds the write in memory; w: "majority" waits until a majority of members hold it, so a failover cannot lose it; j: true adds confirmation that the journal has it on disk. Default write concern became w:majority in 5.0. The tradeoff is latency versus durability, and the professional answer picks per workload: payments get majority with journal acknowledgment, high-volume telemetry often stays at w:1 with its own recovery story, and wtimeout bounds how long any of them will wait.

What are read preferences?

Answer: The choice of where reads run: primary by default, primaryPreferred, secondary, secondaryPreferred, and nearest by ping time. Secondaries serve eventually consistent reads because replication is asynchronous, so stale reads are expected behavior, not a bug. The anomalies worth naming for credit: secondary reads can lag, and during failover they can briefly observe data that later rolls back unless read concern majority backs them. Analytics, caches, and dashboards tolerate that; balances and inventory decisions often do not. Preference choice is a consistency contract, and stating it that way answers the question at the level MongoDB interview questions here are probing.

What are the read concerns, and how do they differ from read preferences?

Answer: Read preference picks which member reads run on; read concern picks what data that member is allowed to return. local returns the member’s own latest view, possibly not majority-committed and possibly orphaned on shards; majority returns only writes committed by a majority; linearizable gives the strongest single-document recency at the highest latency; snapshot provides a consistent point-in-time view inside transactions and consistent sessions. Causal consistency ties sessions together with majority reads plus causal tokens. The preference-versus-concern distinction is precisely what this question grades.

What is rollback, and how do you make it rare?

Answer: When a former primary rejoins after failing with writes that never replicated to a majority, the new primary’s history wins and the unreplicated writes are rolled back, saved as BSON files in a rollback directory for manual recovery. Prevention is the answer they want: w:majority write concern for anything that matters makes rollbacks vanishingly rare, because a write must be majority-committed to survive an election. Monitoring election events and reviewing rollback files after incidents closes the loop. Rollback is the reason write concern exists, which is why these two questions travel together.

What does rs.status() tell you, and what do you read first?

Answer: Member health and roles, each member’s optime, the replication lag between members, election history, and heartbeat round-trip times. First reads in any incident: is every member healthy, how far is each secondary’s optime behind the primary, and are heartbeats clean. rs.conf() complements it with votes, priorities, and hidden or delayed member settings, and rs.printSecondaryReplicationInfo() prints a plain lag table. Lag numbers plus heartbeat times decide most replication diagnoses before any log is opened, which is why this command anchors the replica set tier.

What makes a good shard key?

Answer: Three data properties and one query property. High cardinality, so the key space splits into many chunks; low frequency, so no single value pools into a hotspot; non-monotonic change, so inserts spread across shards instead of appending to the last chunk forever. The query property: your most common queries should include the key, so mongos routes them to one shard instead of broadcasting. Perfect single fields rarely exist, which is why compound keys like { user_id: 1, order_id: 1 } are the working answer. Every sharding topic downstream in MongoDB interview questions is an application of this one answer.

Hashed sharding versus ranged sharding: how do you choose?

Answer: Ranged sharding keeps key order: range queries on the key hit few shards, but sequential key values pile inserts onto one shard. Hashed sharding hashes the key value: writes spread immediately and evenly, but range queries on that key scatter to every shard. The choice reads from the workload: lookup-heavy event and telemetry systems with even write pressure favor hashed, and time-series systems that need recent-window scans favor a compound ranged key whose leading field is non-monotonic. Naming the tradeoff, not picking a winner, is what this answer requires.

What are chunks, and what does the balancer do?

Answer: A chunk is a contiguous range of shard key values, on the order of 128 MB in current releases, that lives on exactly one shard. Chunks split when they outgrow the size threshold, a metadata-only operation, and the balancer migrates chunks between shards in the background whenever data distribution drifts, throttled and schedulable by window. Oversized unsplittable jumbo chunks, usually from terrible key cardinality like a boolean field, resist both splitting and moving. Chunk behavior is the mechanics behind every shard balancing story and behind most scaling-flavored MongoDB interview questions, so narrate split, migrate, and jumbo in that order.

Why does a monotonic shard key create a hotspot?

Answer: Keys that always increase, timestamps and auto-increment ids being the usual suspects, map every new insert to the maximum key range, which lives on exactly one shard. Unlimited write scalability collapses into one machine’s disk queue while the rest of the cluster idles, and the balancer cannot help because new data keeps arriving at the same edge. Fixes are hashed keys or compound keys with a leading high-cardinality non-monotonic field. The phrase hotspot shard is what interviewers wait for in this answer, and the mechanism sentence above is what earns it.

What is targeted routing versus scatter-gather?

Answer: When a query includes the shard key, mongos consults chunk metadata and sends it only to the shards owning those ranges, a targeted query whose cost stays flat as the cluster grows. Without the key, mongos broadcasts to all shards and merges the results, a scatter-gather costing the sum of every shard’s work. Hot lookups that omit the key degrade the cluster linearly with shard count, which is why key inclusion belongs in hot paths by design. Explaining both terms with the same sentence structure is exactly what performance-focused MongoDB interview questions reward here.

Application queries mongos query router Config servers chunk ranges and cluster metadata Shard 1 replica set, chunks a to f Shard 2 replica set, chunks g to m Shard 3 replica set, chunks n to z Key in query: targeted to one shard. Key missing: scatter-gather to all shards reads metadata broadcast
mongos reads chunk ranges from the config servers, targets shards holding the queried key, or broadcasts when the key is absent.
How do multi-document transactions work?

Answer: Available on replica sets since 4.0 and sharded clusters since 4.2: open a session, call startTransaction, and the reads and writes inside commit atomically with snapshot read concern, or abort as a unit. Runtime limits shape usage: a 60-second default lifetime, and every participant must hold the work until commit, so long or huge transactions pressure cache and oplog. The design guidance interviewers want: transactions are for correctness cases, and good document modeling usually removes the need. Retryable and short is the professional shape for the ones that remain.

What does atomicity of a single-document write mean in practice?

Answer: Every write touching one document is atomic and isolated: concurrent readers see either the fully old or fully new version, never a half-updated document, regardless of how many fields or array elements the write changes. That guarantee is the real reason the modeling advice says put data that must change together into one document: you get transaction semantics for free, sized to one document’s 16 MB envelope. Multi-document needs beyond that envelope are what transactions exist for. This single mechanism explains a surprising fraction of schema design questions, so connect the two out loud.

What is journaling, and how does it protect committed writes?

Answer: WiredTiger’s write-ahead log: writes are recorded to an on-disk journal, batched and synced on a short interval or immediately with j: true write concern, so after an unclean shutdown the server replays the journal over the last checkpoint and recovers to a consistent state without manual repair. Checkpoints bound how much replay is needed; the journal covers the gap. The operational notes worth adding: journal and data disks should both survive, journal sync settings are what turn w:1 from memory-only to durable-at-this-node, and journal behavior alone answers a surprising number of durability MongoDB interview questions.

Which hard limits should every MongoDB engineer know?

Answer: The 16 MB document limit, intentional, protecting working sets and network paths from monster documents; maximum BSON nesting depth of 100 levels; namespace names capped at 255 bytes; and the historical index key length limit, removed in 4.2. Document growth toward 16 MB is the one that bites in production, usually through unbounded arrays, and it fails the write at the worst time. Field names with dots and dollar signs, restricted historically, became storable in 5.0 but remain awkward for queries. Limits questions check whether you design within the envelope or discover it in incidents.

What are the backup options, and how do you choose?

Answer: In rough order of production grade: storage or filesystem snapshots taken with journal consistency, near-instant and restorable in place; continuous backup tooling, Ops Manager, Atlas backups, Percona Backup for MongoDB, adding oplog capture for point-in-time restore; delayed secondaries as a human-scale time machine; and mongodump as the simple, slow fallback. Choose by RPO and RTO: how much data loss is tolerable and how fast must recovery finish, then size the solution to that. Saying RPO and RTO and matching tools to them is exactly what backup-flavored MongoDB interview questions grade.

Why is mongodump considered the weak backup choice?

Answer: It reads every document through the server, so large datasets take hours and load the primary exactly when you least want it; restores rebuild every index from scratch, often longer than the dump took; and without --oplog it is consistent only per collection, not across the deployment. For exports, small datasets, and migrations it is perfectly fine. For a two-terabyte cluster at three in the morning it is the wrong tool, and snapshots or continuous backup win on every axis that matters during an incident. The judgment, not the flag list, is the answer.

How does oplog-based point-in-time recovery work?

Answer: Continuous backup tools take a base snapshot, then persist every oplog entry after it; restoring to a chosen moment replays the oplog from the snapshot up to exactly that timestamp. That is the machinery behind restoring to 14:32, just before the bad migration, on replica sets and sharded clusters alike. Change streams can feed the same pattern into data lakes and secondary systems for other consumers. The phrase to use out loud is snapshot plus oplog replay equals point-in-time recovery, and the recovery-window sizing question is its natural follow-up.

How do you monitor a MongoDB deployment?

Answer: Built-in tooling first: mongostat for live operation rates, queues, and WiredTiger cache dirty and used percentages; mongotop for read and write time per collection; then exporters feeding Prometheus or the cloud control plane for history and alerts. The metrics that earn pages: replication lag, cache dirty and used percentages, opcounters against capacity, connection counts, oplog window, and queue depth. Monitoring is how every scenario question starts with data instead of guesses, and being able to name your five page-worthy metrics is the whole answer.

Scenario and troubleshooting MongoDB interview questions

This tier is how scenario rounds actually feel: one symptom sentence, then the interviewer goes quiet while you think out loud. The graded skill is identical in every item below: state your order of checks and the reasoning between them, then act. Silence plus random flag-tuning loses to a spoken diagnostic plan almost every time, and that plan is precisely what these MongoDB interview questions are measuring.

A query that took 40 milliseconds yesterday now takes 20 seconds. Walk me through the diagnosis.

Answer: Order: reproduce it in explain with executionStats verbosity and read the plan first, because a COLLSCAN or an exploding docsExamined against nReturned ends most investigations immediately. Second, check $indexStats and getIndexes(), since a deploy may have changed query shape or dropped an index. Third, pull the actual query text from the profiler and confirm the shape matches what you explained, including types, because a string versus number mismatch silently skips indexes. Only then look at cache pressure. Fix by index design using ESR ordering, not by server knobs, and that discipline is what scenario MongoDB interview questions reward here.

You must pick a shard key for a 5 TB collection before launch. What is your process?

Answer: Inventory queries first: which filters and sorts dominate production traffic, because the key should appear in them. Then evaluate candidate keys against the three data properties: cardinality, frequency, and monotonic change. Choose compound ranged keys matching hot queries, or hashed keys for even write spread on lookup-heavy workloads, and pre-split ranges before load so chunks start distributed. Test with representative data volumes and watch the balancer. Changing the key after launch means resharding, so treat this as a one-way door and say so. That respect for the decision is the point, and senior MongoDB interview questions usually open with exactly this process.

The team shipped with a monotonic timestamp shard key and every insert hammers one shard. What now?

Answer: This is the classic bad shard key migration. On 5.0 and later, reshardCollection changes the key online: it copies data through a shadow phase while writes continue, at a cost you schedule and throttle for quiet hours. On older versions the path is manual: build a new collection with the correct key, dual-write during backfill, switch reads, then retire the old one. Whichever route, stop the bleeding first by spreading write pressure if possible. The sentence that lands: prevention, hashed or compound keys, is cheaper than any migration, which is why this scenario appears so often.

Reads randomly return data a few seconds old, and different app servers disagree about recent writes. What is happening?

Answer: Asynchronous replication plus secondary reads: read preferences are spreading reads to secondaries that lag the primary, so each client sees a different snapshot. Confirm with rs.status() lag numbers and watch them during the discrepancy window. Then fix by contract, in order: route consistency-critical reads to the primary, use read concern majority or causal consistency sessions where you must read secondaries, and separately attack the lag itself, since write bursts and slow secondary disks are the usual sources. Naming causal consistency and what it guarantees is the detail that finishes this scenario cleanly, and stale reads sit near the top of scenario MongoDB interview questions because they are so easy to misdiagnose.

mongod sits at 95 percent RAM, page faults climb, and latency spikes at peak. What do you do?

Answer: The working set has outgrown the WiredTiger cache. Confirm from serverStatus: cache bytes versus maximum, eviction rates, and dirty percentage, plus the fault columns in mongostat. Triage in order: missing indexes dragging cold pages in through scans, check the profiler and $indexStats; oversized documents bloating every touch; then capacity, raising the cache only after confirming the OS is not swapping, and adding RAM or sharding when the hot set genuinely exceeds the box. Shrinking the working set beats every tuning flag, saying that first is the senior answer to this scenario, and capacity stories like it anchor the platform side of MongoDB interview questions.

An embedded comments array keeps growing, documents are near 16 MB, and writes slow down. How do you fix the design?

Answer: Stop embedding unbounded lists; the growth pattern itself is the diagnosis. Options in order: move comments to their own collection indexed by parent id and created_at, which paginates cleanly and removes the 16 MB ceiling; apply the bucket pattern, batching a fixed number of comments per document when they must stay near the parent; use the outlier pattern for the rare huge threads. Migrate with a batched backfill script, dual-write during the window, and verify counts before cutting over. Bounded arrays belong in documents, unbounded ones never do, and naming two patterns is what completes this answer.

Before: one document post document comments: [ … unbounded … ] 16 MB ceiling, slow writes After: post document small, stable size Bucket 1 50 comments, count field Bucket 2 next 50, indexed by parent migrate Writes fill the current bucket; a new bucket opens when it reaches the cap. Unbounded array to bucket pattern
The bucket pattern caps each document at a fixed comment count, keeping every write small and the 16 MB ceiling unreachable.
Someone dropped a collection in production. What are your recovery options?

Answer: Freeze the scene first: stop application writes, because every new oplog entry shrinks the window you can recover from. Then in order of speed: export from a delayed secondary holding a pre-drop copy, restore snapshot plus oplog replay to just before the drop into a side cluster and copy the collection back, use continuous backup tooling if you have it, and fall back to your last mongodump only in desperation. Verify the recovered collection before writing it back. Recovery quality is bounded by oplog window and backup cadence, stating that boundary is the real lesson of this scenario, and recovery drills are the heart of scenario MongoDB interview questions for precisely that reason.

Replication lag alerts fire every night during batch jobs. How do you stop the secondaries falling behind?

Answer: Lag means secondary apply cannot keep up with primary write volume, so the fix is rate, not configuration heroics. In order: chunk the batch into smaller units with pauses between them, spread the window off-peak, confirm secondary disk throughput and cache pressure are not the true bottleneck, and check the batch is not doing unindexed scans that multiply rewritten data. A larger oplog prevents stale members but does nothing for lag, which is the distinction to state, and lag remains a fixture of MongoDB interview questions because every busy cluster meets it eventually. If the batch is genuinely huge, it belongs on a separate cluster fed by change streams; saying that shows the escalation ladder.

The primary stepped down twice last night. How do you investigate elections?

Answer: Build the timeline before touching anything: election events in the mongod logs plus rs.status() history, noting which member called the election and why the old primary was judged gone. Common causes in order: network blips between members so heartbeats miss, a primary starved on disk or CPU and slow to answer heartbeats, so check iostat around the window, and configuration, priorities or a recent replSet reconfig. Match every log line to a metric before concluding. Restarting things first destroys the evidence, saying you will not do that is exactly what this scenario grades, and election investigations are where DevOps-flavored MongoDB interview questions find their depth.

Inserts slowed cluster-wide and iostat shows saturated data disks. What do you check?

Answer: Walk the write path in order: journal syncs, checkpoint pressure, then index maintenance. Read the WiredTiger cache dirty percentage, since high dirty water marks stall checkpoints and everything behind them; count indexes on the hot collection, because every write updates every index; check compression settings and whether heavy readers or backup jobs share the disks. Fixes follow the same order: drop dead indexes found with $indexStats, batch smaller writes, move or upgrade storage, and push heavy reads to secondaries. mongostat and mongotop decide, not intuition, and naming that discipline is the answer at the depth MongoDB interview questions expect.

A $lookup-heavy aggregation times out in production. How do you make it survive?

Answer: Read the plan first: the foreign collection’s join field must be indexed, otherwise every left-side document scans the right side, which is the single most common cause. Then push $match as early as possible, avoid unbounded $unwind fan-out before filtering, and consider allowDiskUse for the blocking stages. If it still hurts, question the model: denormalize the joined fields into the parent, or cache the pipeline output for hot dashboards. Pipelines with indexed joins and early filters survive; per-request joins over whole collections never will, and that sentence ends this scenario well.

mongos suddenly fans simple lookups out to every shard. How do you find and fix the scatter-gather?

Answer: Explain the query through mongos and look at which shards answered: a targeted query hits one, a scatter-gather hits all. The cause is almost always the shard key missing from the query, or a type mismatch, string versus ObjectId being the classic, that silently defeats key matching. Fix in application code by including the key in hot lookups, fix the type mismatch at the driver layer, and for lookups that legitimately lack the key, accept the broadcast on a secondary or add an index-only strategy. Re-verify with the same explain after the fix, because that before-and-after is the deliverable.

The balancer migrates chunks constantly and I/O spikes across shards. What do you tune?

Answer: First ask whether the migrations are legitimate: check per-shard data distribution, because a genuinely skewed cluster is the balancer doing its job after an incident or a launch. If shards are near even, constant migrations point at jumbo chunks, oversized unsplittable ranges that migrate forever, or a badly chosen key. Tuning in order: set a balancing window for off-peak hours, split and migrate jumbo chunks manually, and consider zone sharding to pin hot ranges deliberately instead of letting drift dictate placement. Measure imbalance, schedule movement, kill jumbos: that order is the complete answer, and balancer behavior is a reliable scenario in MongoDB interview questions for anyone running a sharded cluster.

Writes fail with WriteConflict errors under a transactional workload. What is happening and what do you fix?

Answer: Two transactions touched the same documents and WiredTiger’s optimistic concurrency aborted one; MongoDB returns WriteConflict and expects a retry, which drivers’ transient transaction APIs handle with backoff. Fix in order: add the retry wrapper first, shorten transactions by moving non-database work outside them, reduce contention on hot documents by reworking read-modify-write counters into queue or increment patterns, and verify each transaction’s document set is as small as possible. Most transaction trouble is contention wearing a costume, and saying that line plus naming the retry expectation is what closes this scenario.

Transactions abort at the 60 second limit during a migration job. What do you change?

Answer: The default transactionLifetimeLimitSeconds is 60, and raising it is a band-aid that increases cache pressure and oplog bloat. Restructure instead: chunk the migration into many small transactions keyed by id ranges, scan with snapshot reads outside transactions and write in idempotent batches, so a failed unit retries safely without redoing everything. Keep a progress marker document so the job resumes where it stopped. Bounded, idempotent units of work beat one giant transaction on every axis: lifetime, memory, retry cost. That redesign sentence is the answer they wait for.

One shard’s disk is nearly full while the others are fine. Why does that happen and what do you do?

Answer: Three usual causes: unsharded collections, including system databases, live on the primary shard and never balance; a lopsided chunk distribution from a paused or failed balancer; and jumbo chunks pinning data to one shard. Diagnose with sh.status() and per-shard disk numbers. Fixes follow: confirm the balancer is running, split and move jumbo chunks with explicit commands, and move unsharded collections off the primary shard deliberately. Alert on per-shard disk, never cluster average, because this exact asymmetry is invisible to averages, which is the prevention sentence to end on.

Connections climb into the tens of thousands and mongod slows. What is your playbook?

Answer: Every connection costs memory and scheduling, so start by comparing current connections against the configured maximum and watching the rate: a climb is a leak, not load. The usual culprits are application instances opening a pool each, serverless functions creating per-invocation clients, and missing pool caps after a scaling event. Fix in order: cap and share client pools as singletons, right-size pool sizes to actual concurrency, raise maxIncomingConnections and ulimits only after the client side is proven sane, and add connection-count alerts. Restarting mongod without fixing the leak just resets the clock, and saying so is the point, because connection storms have become a modern staple of MongoDB interview questions thanks to serverless clients.

After a failover, the app throws not primary errors for a minute. How do you make elections survivable?

Answer: Elections are a when, not an if, so the application must ride them. Enable retryWrites and retryReads in the connection string, keep drivers current, and make writes idempotent, upserts and increments instead of absolute sets, so a retried write cannot double-apply. Server side, clean priorities and healthy heartbeats shorten the window. Also confirm the driver pool replaces the old primary’s sockets instead of caching a dead handle. The graded pairing is retries plus idempotency: retries alone on non-idempotent writes convert an election into duplicate effects, which is worse than the error.

After an unclean shutdown, how do you verify data integrity?

Answer: Expect journal replay at startup and read the log for recovery lines and any WT errors. Then in order: run db.collection.validate() on critical collections to check documents and index consistency, compare dbHashes between members to confirm replication integrity, and watch the first hours for latency anomalies from cache rebuilding. If validate reports corruption, restore from backup into a side cluster and surgically replace the affected data; never run repair casually on a live set, since it takes the member down and can drop data it cannot salvage. The ordered checklist is the answer, and unclean-shutdown drills appear in MongoDB interview questions whenever reliability is on the menu.

The profiler shows hundreds of COLLSCANs in production, but the same queries use indexes in dev. Why?

Answer: Environments drift, so diff them in order: compare getIndexes() output between environments first, because migrations that were never applied to prod are the most common cause. Then compare actual query shapes from the profiler entries, since feature flags change filters. Finally check stored data types, because a field holding strings in one environment and numbers in another silently defeats index matching. The prevention sentence: indexes belong in migration scripts applied everywhere, never in console history. Naming the diff order, indexes, shapes, types, is exactly what this scenario measures.

An updateMany matched millions, the application timed out, but mongod is still working. What do you do?

Answer: Decide deliberately, because per-document atomicity means a killed operation leaves partial updates with no rollback. Check progress and identity in currentOp: the opid, its plan, and its nmatched counter. If the update is idempotent and correct, letting it finish while you block re-triggers is usually cleanest. If it must die, db.killOp(opid), then reconcile the partial state with a resumed run. Prevention: bulk mutations belong in batched scripts with maxTimeMS and logging, never in a request path. The judgment spoken out loud, finish versus kill versus reconcile, is the graded content here.

A TTL index is not deleting expired sessions fast enough. What do you check?

Answer: Verify the index shape first with getIndexes(): single field, BSON date, expireAfterSeconds set, because a string date or wrong field silently deletes nothing. Then understand the mechanism: the TTL monitor passes roughly every 60 seconds and deletion competes with live write load, so large backlogs lag behind. Check whether the application refreshes timestamps on read, a classic self-inflicted storm that keeps rescheduling expiry. For bulk expiry pressure, an explicit batched delete during quiet hours or fixed-window buckets beats fighting TTL throughput. TTL is lazy cleanup, not a scheduler, that sentence is the takeaway, and TTL troubleshooting is a favorite mid-round detour in MongoDB interview questions.

A $group stage fails with exceeded memory limit. What are your options?

Answer: The stage crossed the 100 MB per-stage limit. Options in cost order: push $match earlier and make it index-backed, reduce group cardinality or aggregate in two passes, set allowDiskUse: true to spill correctly but slowly, and for recurring dashboards, pre-aggregate into summary collections updated incrementally. Check whether an index can satisfy a feeding $sort too, since that often removes the biggest allocation. Moving genuinely heavy analytics to a warehouse or a dedicated secondary is the structural fix. Knowing the exact limit and ordering options by cost is what scenario MongoDB interview questions want from this one.

A bad migration ran at 14:32 and you need point-in-time recovery. What is the runbook?

Answer: Verify coverage first: a base snapshot from before 14:32 plus continuous oplog capture through the incident. Restore the snapshot into a brand new cluster, replay the oplog with mongorestore --oplogReplay and an oplog limit stamped at 14:32, or the tooling equivalent, then validate the recovered collections before anything touches production. Write back only affected data or cut over entirely, never restore in place over the live cluster first. The words they listen for: side cluster, oplog replay, validate, then cutover. Any runbook missing the validation step is how one incident becomes two.

A secondary with a smaller disk filled up and stopped replicating. What are your options?

Answer: Confirm staleness with rs.status(): a frozen optime plus heartbeat health tells you whether it can still catch the oplog window at all. Options ordered by safety: free space on the member, then resync, removing and re-adding it so initial sync rebuilds from current data, ideally onto a right-sized disk. Do not attempt oplog tricks on a full disk; resizing the oplog needs space you no longer have. Prevention is the closing line: identical disk sizing across members, an oplog sized for the longest maintenance window, and disk alerts on every member, not just primaries.

Reporting queries make the OLTP application slow every afternoon. How do you isolate the workloads?

Answer: Isolation beats optimization here, the escalation ladder is the answer, and workload isolation is the closing theme of most senior MongoDB interview questions, so deliver the ladder with confidence. First, route analytics reads to secondaries with a secondary read preference, accepting staleness, and monitor lag so the tradeoff stays honest. Second, constrain what remains on primary hours: maxTimeMS on heavy aggregations, off-peak scheduling, and indexes that serve reporting without scanning production paths. Third, pre-aggregate into summary collections so dashboards stop touching raw data at all. When contention still bites, split analytics onto a dedicated cluster fed by change streams. Naming the ladder in order is what completes this scenario.

Hands-on scenario labs

Reading answers builds vocabulary; the scenario tier of MongoDB interview questions is graded on reflexes, and reflexes take repetition. Each lab below runs on a throwaway Docker instance and is a safe, self-inflicted incident. Do each three times: once with the checklist open, once from memory, once narrating out loud as if an interviewer were listening. That narration is exactly the rehearsal these rounds reward, and the live portions of MongoDB interview questions converge on these same three shapes.

Lab 1: turn a collection scan into a covered query

  • Start mongosh against a scratch instance, create db.orders, and bulk insert 100k documents with insertMany mixing statuses and dates.
  • Run db.orders.find({ user_id: 42, status: "paid" }).sort({ created_at: -1 }) with .explain("executionStats") and confirm the COLLSCAN plus wasted docsExamined.
  • Design the compound index yourself in ESR order, then create it with db.orders.createIndex({ user_id: 1, status: 1, created_at: -1 }) and re-run the same explain.
  • Add a projection of only the indexed fields and verify the FETCH stage disappears and totalDocsExamined hits zero.
  • Write down the before-and-after ratios of keysExamined, docsExamined, and nReturned, because quoting real numbers is what interviewers remember.

Lab 2: break a replica set and survive the election

  • Stand up a three-member replica set locally with Docker, initialize it with rs.initiate(), and confirm one primary with rs.status().
  • Write with writeConcern: { w: 1 }, then kill the primary container and watch the logs for the election and the new primary.
  • Repeat the kill with w: "majority" and confirm the acknowledged writes all survive on the promoted member.
  • Inspect rs.conf(), change priorities, and step the new primary down deliberately with rs.stepDown().
  • Finish by writing the election timeline in your own words: heartbeat miss, timeout, majority vote, promotion.

Lab 3: drill a drop-and-recover end to end

  • Seed a database, then take a baseline copy with mongodump --db lab --out /backup/base.
  • Insert new documents after the dump so the live collection drifts from the backup.
  • Drop the collection on purpose, then restore the baseline with mongorestore --drop --db lab /backup/base/lab and measure what came back.
  • Repeat using a delayed-secondary mindset: note which post-dump writes are unrecoverable and quantify the loss window.
  • Close by writing your RPO and RTO for this drill in one sentence each, because that framing is the senior version of the answer.

Cheat sheet: the commands behind the answers

Nearly every item in this bank of MongoDB interview questions resolves to one of the commands below, in the same order you would reach for them live. Learn the table, then one diagnostic sentence per row, and any scenario round becomes narration instead of improvisation.

CommandWhat it tells you
mongoshThe shell everything else runs in; scripts double as maintenance jobs
show dbs / show collectionsWhat exists where, before you touch anything
db.coll.find({...}).explain("executionStats")Plan plus counters: COLLSCAN or IXSCAN, keys and docs examined, time
db.coll.createIndex({...})Index creation in ESR field order
db.coll.getIndexes()Every index with names and properties, the env-diff opener
db.coll.dropIndex("name_1")Removing dead write tax, after stats confirm it
db.coll.aggregate([{ $indexStats: {} }])Usage counters per index since server start
db.coll.stats()Sizes, counts, and index bytes behind capacity math
db.setProfilingLevel(1, { slowms: 100 })Capturing slow operations into system.profile with real query text
db.currentOp(true)What is running right now, with opids for killOp
db.killOp(opid)Stopping a runaway operation deliberately, knowing partial-write state
db.serverStatus().wiredTiger.cacheCache used and dirty bytes, eviction pressure behind latency
mongostatLive op rates, queues, and cache percentages at a glance
mongotopRead and write time per collection
rs.status()Member health, optimes, lag, and election state
rs.conf()Votes, priorities, hidden and delayed member settings
rs.printSecondaryReplicationInfo()A plain lag table per secondary
db.printReplicationInfo()Oplog window: how far recovery reaches
sh.status()Shards, chunk distribution, balancer state
sh.reshardCollection(ns, key)Online shard key change on 5.0 and later
mongodump --db app --out /backupBSON fallback backup and export
mongorestore --drop --oplogReplay --oplogLimit <ts>Point-in-time restore to just before the incident
db.coll.validate()Document and index consistency after unclean shutdowns

The full manual for every command here lives at mongodb.com/docs/manual, and the replication and sharding sections at mongodb.com/docs/manual/replication cover every mechanism this page touches. Bookmark both: they are the references interviewers themselves open when writing MongoDB interview questions.

Key takeaways and FAQ

The through-line of every tier above: MongoDB interview questions reward people who pair the command with the mechanism that makes it matter. A command alone reads as memorization; a mechanism alone reads as theory; together they read as someone who has carried the pager for a document database. Keep that pairing in every answer you rehearse, and this bank of MongoDB interview questions becomes a script for the whole loop.

How long should I prepare for MongoDB interview questions?

With working experience, a focused week: two days speaking the beginner tier aloud, two on intermediate, one on scenarios, the weekend on the labs. Without daily MongoDB use, plan three to four weeks and run every command against a scratch instance once, because hands recall what eyes skim.

Are MongoDB interview questions different for backend and DevOps roles?

The beginner and intermediate tiers overlap heavily, but the emphasis moves. Backend loops lean into schema design, aggregation, and transactions; DevOps and platform loops push replication, sharding, backups, and the failure modes of each. Prepare the full bank either way, because you cannot predict which half the panel owns.

Which MongoDB interview questions come up most?

Index design with ESR, reading an explain plan, write concern versus read concern, shard key choice, and the unbounded array design trap. If you can narrate one concrete example for each, including a number or a before-and-after, you are ahead of most candidates in any round built on MongoDB interview questions.

Do MongoDB interview questions include live shell work?

Increasingly yes, against a sandbox instance or a small Docker replica set, especially for platform and senior roles. The labs on this page exist for exactly that format, and practicing spoken narration while typing is the single best rehearsal for it.

Which version should I learn for MongoDB interview questions in 2026?

Concepts are stable across 6.0, 7.0, and 8.0: the engine, replication, and sharding mechanics in this bank have not changed fundamentally since 4.4 to 5.0. Learn the modern defaults, majority write concern and online resharding, and say version-anchored sentences like default write concern since 5.0 rather than memorizing changelogs.

What should I read after this page?

Continue with the Linux interview questions and Docker interview questions banks, since MongoDB in production lives on Linux hosts and in containers, then browse the DevOps Prep hub for the rest of the series as it ships.

MongoDB Prep Quiz: Documents, Replication, and Sharding

1 / 5

explain("executionStats") shows docsExamined at 250,000 and nReturned at 12. What does that tell you?

2 / 5

How does a TTL index actually delete expired documents?

3 / 5

An embedded comments array keeps growing toward the 16 MB limit. What is the right fix?

4 / 5

What does write concern w:"majority" guarantee that w:1 does not?

5 / 5

A sharded collection uses a monotonic timestamp shard key. What production behavior do you expect?

0%