Top 30 MongoDB Interview Questions and Answers [2026]
October 11, 2026
14 min read
TL;DR: MongoDB interviews in 2026 test schema design for access patterns, compound index order, aggregation performance, write concern and shard key choice. The current releases are MongoDB 8.3 (minor track, May 2026) and 8.0 (major track, supported to October 31, 2029), and MongoDB 7.0 reaches end of life on August 31, 2027.
Starting with 8.2, MongoDB splits its server into two tracks: a major release every two years with a five-year lifecycle, and minor releases in between that each stop getting patches once the next one ships.
Minor releases cannot be skipped on upgrade, so 8.2 to 8.3 to the next minor is a chain, not a jump. A candidate who can explain which track their team runs, and why, has usually operated MongoDB rather than only queried it.
Key takeaways
1The latest patches are 8.3.11 and 8.0.32, both released on September 11, 2026 with security fixes.
2MongoDB 8.0 deprecated index filters in favor of query settings set with setQuerySettings.
3$lookup has worked with sharded foreign collections since MongoDB 5.1, so the old "you cannot join to a sharded collection" answer is out of date.
4After a primary fails, the median time to elect a new one should not typically exceed 12 seconds with default settings.
Data Modeling
1. When do you embed a document, and when do you reference it?
Embed data that is read together with its parent and belongs to it; reference data that grows without limit, is shared by many parents, or is read on its own.
MongoDB's data modeling docs put the core principle as "data that's accessed together should be stored together", and the limits that override it are the 16 MiB document size and update contention on a single document.
An order's line items and shipping address belong embedded: they are read with the order and never change after it ships.
A product referenced by thousands of orders belongs in its own collection, with the order keeping a copy of the few fields it displays (name, price at purchase).
That copy is deliberate: it records the price at the time of the order, so it is correct for it not to follow later changes.
2. How do you enforce a schema on a collection?
With a $jsonSchema validator on the collection. A common screening exercise: every document in reviews must have username (a string), rating (an integer from 0 to 5) and comments (an array of at most 3 items).
The trap in this exercise.bsonType: "int" checks the BSON type, not the value, so a rating that arrives as the double 4.0 (common when it passes through a float or a JSON parser in another service) fails validation even though it looks like 4. bsonType: ["int", "long"] is a looser alternative.
validationLevel is strict by default; moderate skips updates to documents that were already invalid. validationAction is error by default, warn only logs, and errorAndLog, new in 8.1, does both. See Specify JSON Schema Validation.
3. Why are unbounded arrays a problem, and what is the bucket pattern?
An array that grows forever, such as every reading from a sensor pushed into one document, eventually hits the 16 MiB BSON limit.
Well before that it makes every update rewrite a large document, bloats indexes (a multikey index has one entry per element), and turns the document into a write hotspot.
The bucket pattern caps the growth: one document per sensor per hour, each holding that hour's readings plus a count, min and max. Queries read a few dozen buckets instead of thousands of tiny documents.
For measurements over time, a time series collection (question 5) now applies this pattern automatically.
4. Which schema design patterns do you use most?
A strong candidate names the pattern and the query it serves:
Extended reference: copy a few fields of a related document (a customer's name on an order) to avoid a $lookup on the hot read path.
Subset: keep the 10 most recent reviews embedded in the product, the rest in a reviews collection.
Computed: maintain a running total or count on write instead of aggregating on every read.
Outlier: handle the rare document with 50,000 followers differently (an overflow flag and a separate collection) instead of designing everything around it.
Schema versioning: store a schemaVersion field and migrate documents lazily when they are next written.
Each pattern trades write cost or duplication for read speed, and the answer should say what keeps the copies consistent.
5. When would you use a time series collection?
For measurements that arrive over time from a source, such as metrics, IoT readings or prices.
You declare a timeField and an optional metaField that identifies the source, and MongoDB groups documents into internal buckets by source and time, compressing them and indexing the time field.
The metaField is fixed at creation and should hold values that rarely change.
Time series collections are built for inserts and range reads; frequent updates or deletes of individual measurements are a sign the data belongs in a normal collection. See Time Series.
6. In a MERN or Node.js app, what does Mongoose add over the native driver?
Mongoose adds application-side schemas, casting, validation, middleware hooks and populate() for references. The native driver sends what you give it. Mongoose is useful when a team wants one place to define document shape in code.
The trade-offs a senior candidate should raise: Mongoose validation runs only in the application, so a script or another service can still write bad data unless the collection also has a $jsonSchema validator; populate() issues extra queries from the application rather than a server-side join; and hydrating full model instances is slower than .lean() reads, which return plain objects.
Indexes and Queries
7. How do you order the fields in a compound index?
Follow the ESR guideline: fields tested for Equality first, then fields used to Sort, then fields with Range conditions.
For find({ status: "open", total: { $gt: 100 } }).sort({ createdAt: -1 }) the index is { status: 1, createdAt: -1, total: 1 }.
Putting the range field before the sort field breaks the sort: the index would return rows ordered by total, and MongoDB would have to sort in memory.
Equality on a field with very few values can still go first, because an equality match on any value keeps the rest of the index in order. See the ESR guideline.
8. What do you look for in explain("executionStats")?
Compare three numbers: nReturned, totalKeysExamined and totalDocsExamined. On a well-indexed query all three are close.
Keys far above returned means the index is not selective for this query; documents far above keys means the filter is applied after fetching.
COLLSCAN in the winning plan: no usable index.
A SORT stage: the index does not provide the order, so the sort runs in memory.
FETCH after IXSCAN is normal; its absence means the query was covered.
On a sharded cluster, explain also shows which shards ran the query, which is how you catch a scatter-gather query (question 21).
9. How do multikey indexes work, and what are their limits?
Indexing an array field creates one index key per element, so { tags: 1 } finds every document whose tags contains a value. MongoDB marks the index multikey automatically the first time it sees an array.
Two limits come up in interviews. A compound index can have at most one field whose value is an array in any given document, so { tags: 1, categories: 1 } fails if a document has arrays in both.
And a multikey index cannot cover a query on the array field, because each key holds only one element, not the whole array.
10. When do you use partial, TTL and wildcard indexes?
Partial: index only documents matching a filter, such as { status: "active" }. Smaller and cheaper to maintain; the query must include the filter condition to use it. Preferred over sparse indexes for new work.
TTL: a single-field index on a date with expireAfterSeconds. A background task deletes expired documents, so expiry is not instant.
Wildcard: { "attributes.$**": 1 } indexes arbitrary fields under a path, for user-defined attributes you cannot predict. It is a fallback, not a replacement for targeted compound indexes.
11. What is a covered query?
A query answered from the index alone, with no document fetch. Every field in the filter and the projection must be in the index, and the projection must exclude _id unless _id is part of the index.
In explain output, totalDocsExamined is 0 and there is no FETCH stage.
Filter and shrink documents as early as possible, and let an index do the first stage. A $match or $sort at the start of the pipeline can use an index; the same stage after a $group or $unwind cannot.
The optimizer moves some stages forward on its own, but a pipeline written in the right order does not depend on it.
Each stage has a 100 MB memory limit.
Since MongoDB 6.0 the allowDiskUseByDefault parameter decides whether stages above that limit spill temporary files to disk or fail; spilling works, but it is a signal that the pipeline processes more data than it should.
13. What does $lookup cost, and when should you avoid it?
$lookup is a left outer join: for each input document it queries the foreign collection.
With an index on the foreign field, that is an index lookup per document; without one it is a collection scan per document, which is where most slow $lookup pipelines come from.
It has worked with sharded foreign collections since 5.1, so "it cannot be used on a sharded collection" is outdated.
The better question is whether the join belongs on the hot path at all: if every page view needs it, an extended reference (question 4) is usually cheaper than joining on every read.
14. How do you paginate large result sets?
With a range on an indexed, unique sort key, not with skip(). skip(100000) still walks past 100,000 index entries, so each page gets slower the deeper the user goes.
For a non-unique sort key such as createdAt, add _id as a tiebreaker in both the sort and the range condition, or rows with equal timestamps get skipped or repeated between pages.
Consistency
15. What do write concern and read concern control?
Write concern says how many members must acknowledge a write before the driver reports success.
Read concern says which data a read may return. { w: "majority" } is the default write concern for most deployments: a majority-acknowledged write survives a primary failover, while a w: 1 write can be rolled back if the primary fails before replicating it.
w: 1
Acknowledged by the primary only
Lowest latency
Can be rolled back after a failover
w: "majority" (default)
Acknowledged by a majority of voting members
Adds a replication round trip
Survives a primary failover
Read concern "majority" returns only data a majority has acknowledged, so it can never be rolled back; "local", the default for most reads, may return data that later disappears in a rollback. "linearizable" gives the strongest guarantee for single-document reads, at the cost of a round trip to confirm the primary.
16. When should you use a multi-document transaction?
When several documents must change together and the model cannot put them in one document, such as a transfer between two account documents.
Single-document writes are already atomic, so a good schema needs transactions less often than a relational one.
By default a transaction must finish within 60 seconds (transactionLifetimeLimitSeconds).
The driver's withTransaction helper retries on TransientTransactionError and on unknown commit results, which hand-written transaction code often forgets. Long transactions also pin WiredTiger cache, so keep them small.
You may read stale data. Replication is asynchronous, so a secondary can lag the primary, and a user who writes then reads from a secondary may not see their own write.
Read preference secondaryPreferred suits analytics and reports; it does not add write capacity and it does not fix a slow primary if the secondaries are just as loaded.
When a client needs to read its own writes from secondaries, use a causally consistent session with majority read and write concern. maxStalenessSeconds excludes secondaries that lag too far.
18. What are retryable writes?
Drivers automatically retry certain write operations once after a network error or when no healthy primary is found, such as during an election.
The server records the transaction number of the write, so a retry of a write that had already succeeded is not applied twice.
Retryable writes are on by default in current drivers. Writes with w: 0 are not retryable, and an application still needs its own idempotency for anything larger than a single write, such as a multi-step workflow. See Retryable Writes.
Replication and Sharding
19. What happens when a replica set primary fails?
The secondaries notice the primary has been unreachable for longer than electionTimeoutMillis (10 seconds by default), and an eligible secondary calls an election.
The member that wins a majority of votes becomes primary, and drivers discover it and route writes there.
MongoDB documents a median of no more than 12 seconds from failure to a new primary with default settings.
Writes acknowledged only by the old primary (w: 1) and not yet replicated are rolled back when it rejoins, which is the practical argument for majority write concern.
A set needs an odd number of voting members, so a two-data-node set adds an arbiter or, better, a third data node. See Replica Set Elections.
20. How do you choose a shard key?
Pick a key with high cardinality, an even spread of values, and that appears in most queries. Three failure modes:
Low cardinality (country): data cannot split beyond the number of distinct values, and one value can grow into a chunk that cannot move.
Monotonic values (createdAt, an ObjectId): every insert lands on the shard holding the highest range. A hashed shard key spreads inserts but gives up efficient range queries.
Absent from queries: every read becomes a broadcast to all shards.
A compound key such as { tenantId: 1, _id: 1 } often balances these.
The choice is less permanent than it used to be: reshardCollection changes the key online, and since 8.0 it can also reshard on the same key to spread data onto new shards. See Choose a Shard Key.
21. What is the difference between a targeted and a scatter-gather query?
A targeted query includes the shard key (or its prefix), so mongos sends it only to the shards that own that range. A scatter-gather query lacks it, so mongos sends it to every shard and merges the results.
Scatter-gather is fine for rare admin queries; on the main read path it means every shard does work for every request, and adding shards stops adding capacity.
22. What does the balancer do, and what is a jumbo chunk?
The balancer moves ranges of data (chunks) between shards so each holds a similar amount. The default chunk size is 128 MB.
A jumbo chunk is one that has grown past the limit and cannot be split, because all its documents share one shard key value; the balancer cannot move it, and that shard stays overloaded.
Jumbo chunks are a shard key design problem: the fix is a key with more cardinality, now possible online with reshardCollection.
MongoDB 8.0 also added moveCollection, which moves an unsharded collection to another shard, and unshardCollection.
23. How do change streams work, and what can go wrong?
A change stream is a cursor over the oplog that returns insert, update, replace and delete events for a collection, database or deployment, filtered by an aggregation pipeline.
Each event's _id is a resume token: store it, and after a crash the consumer resumes from where it stopped.
The catch is the oplog window. If the consumer is down longer than the oplog covers, the token falls off the oplog and the stream cannot resume, so a full resync is needed.
Since 6.0, collections can store pre- and post-images, so events can include the document as it was before an update. See Change Streams.
24. How do you find what is slowing down a MongoDB deployment?
Start with the slow query log (operations over 100 ms are logged by default) or the database profiler, and look for plans with a COLLSCAN, an in-memory SORT, or a large ratio of documents examined to returned.
On Atlas (M10 and above), $queryStats aggregates statistics by query shape, so the most expensive query pattern stands out over the slowest single run.
At the server level, check the WiredTiger cache.
Its default size is the larger of 50% of (RAM minus 1 GB) or 256 MB, and when the working set outgrows it, reads go to disk and latency climbs across all queries. db.currentOp() shows long-running operations and lock waits right now.
MongoDB 8.2: first minor release available on-premises
May 4, 2026
MongoDB 8.3: $scoreFusion GA, array index variables
Jul 31, 2026
MongoDB 8.2 reaches end of life
Aug 31, 2027
MongoDB 7.0 reaches end of life
25. How does MongoDB's release model work now?
Per the versioning page, major releases (7.0, 8.0) ship every two years with a five-year lifecycle.
Minor releases (8.2, 8.3) add features in between; starting with 8.2 they are also available for self-managed Community and Enterprise deployments, not only Atlas.
The catch is support: once a new minor ships, the previous minor gets no more patches, and minors must be upgraded in sequence.
The lifecycle table lists 8.2 as end of life on July 31, 2026, 8.0 on October 31, 2029, and 7.0 on August 31, 2027.
A team that wants a predictable support window stays on 8.0; a team that wants new query features takes the minors and commits to upgrading with each one.
26. What did MongoDB 8.0 change?
The 8.0 release notes list several changes that come up in interviews:
Cross-collection bulkWrite: the new bulkWrite database command runs inserts, updates and deletes against multiple collections in one request; the notes cite up to 56% faster bulk writes than 7.0.
Sharding moves: moveCollection relocates an unsharded collection to another shard, unshardCollection reverses sharding, and resharding can keep the same key.
Queryable Encryption range queries: $lt, $lte, $gt and $gte on encrypted fields.
Query settings replace index filters (question 27).
27. What are query settings, and why did they replace index filters?
A query setting attaches planner instructions, such as which indexes to consider, to a query shape: the query with its literal values removed.
You add one with setQuerySettings, remove it with removeQuerySettings, and list them with a $querySettings stage.
Index filters, deprecated in 8.0, were stored in memory per node and lost on restart.
Query settings persist across the cluster, which makes them a practical emergency fix when a plan regresses in production and changing the application code would take days.
From 8.3, MongoDB also backfills a representative query for settings created from a query shape hash.
28. Which 8.2 changes affect production clusters?
Safer secondary reads during migrations: a new terminateSecondaryReadsOnOrphanCleanup parameter, on by default, kills long secondary reads before orphaned documents are deleted after a chunk migration. Before 8.2 such reads could silently miss documents. The default orphanCleanupDelaySecs rose from 900 to 3600.
Index builds during initial sync use 10% of available RAM by default, a change also backported to 8.0.13 and 7.0.26.
Performance: the notes cite faster initial sync, faster time series bulk inserts and cheaper multi-planning.
The first item is the one to ask about: a candidate who runs analytics on secondaries of a sharded cluster should know their long queries may now be terminated.
29. What is Queryable Encryption, and how is it different from encryption at rest?
Encryption at rest protects files on disk; the server still sees plaintext in memory and in query results.
Queryable Encryption encrypts fields in the client driver before they leave the application, so the server stores and indexes only ciphertext and never holds the keys, yet it can still answer equality queries and, since 8.0, range queries on those fields.
MongoDB 8.2 added prefix, suffix and substring queries on encrypted strings as a public preview, and the release notes say not to enable them in production.
Candidates should also know the cost: encrypted fields need a key management setup and add storage for the encrypted index data.
30. What did MongoDB 8.3 add?
The 8.3 release notes, for a release that shipped on May 4, 2026, include:
$scoreFusion is GA, joining $rankFusion for combining the results of several pipelines, typically a full-text search and a vector search, into one ranked list.
Array element indexes in $map, $filter and $reduce, including a new $$IDX variable.
New expressions: $hash for MD5, SHA-256 or XXH64 hashes, and Extended JSON conversion with $serializeEJSON.
removeShard is deprecated, and query memory use is now reported per operation in logs and explain output.
Signs of a Strong Answer
They start a schema from the application's queries and say which query each embed or copy serves.
They order compound index fields by ESR and can explain why a range before a sort forces an in-memory sort.
They know w: 1 writes can be rolled back after a failover, and choose write concern per operation.
They reject a monotonic shard key without prompting and know resharding is now online.
They read totalDocsExamined against nReturned before proposing an index.
They can say whether their team is on the major or minor release track and when it goes out of support.