MongoDB interview questions and answers, from data modeling to sharding
MongoDB interview questions center on modeling documents for the queries you will run: when to embed and when to reference, which compound index serves a query, and how to build an aggregation pipeline. Experienced candidates also get replica sets, read and write concerns, multi-document transactions and the shard key decision, which is the hardest to undo. Strong answers start from the access pattern and the failure mode, not from the syntax.
By Evin JohnPublished 9 min read
Where MongoDB shows up in interviews
MongoDB questions appear in Node.js and full-stack backend interviews, in data platform roles that run it at scale, and in system design rounds whenever someone proposes a document store. A backend interviewer usually hands you an app (a blog, a marketplace, an IoT feed) and asks for the collections, a few queries and their indexes. A database or platform interviewer asks how the cluster behaves during an election, how much data a write concern can lose, and what happens when a shard key was chosen badly.
- ScreenConcept checks: documents and BSON, _id, embed versus reference, index types, replica set roles.
- Modeling and query roundDesign collections for a feature, write find and update queries, then an aggregation pipeline for a report.
- Performance and operationsRead an explain plan, fix a slow query, reason about replication lag, write concern and sharding.
Fundamentals: documents, _id and atomicity
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a document, and what is BSON? | Data model | A document is a set of field-value pairs stored as BSON, a binary format with more types than JSON: dates, 64-bit integers, decimals, ObjectId and binary data. |
| What is an ObjectId made of? | Identity | Twelve bytes: a timestamp in seconds, a random value and an incrementing counter. IDs created later sort roughly later, which matters for shard keys. |
| What is the maximum size of a document? | Limits | 16 MB. Hitting it usually means an unbounded array or a file that belongs in GridFS or object storage. |
| What operations are atomic? | Consistency | Any write to a single document, including nested fields and arrays, is atomic. Changes across documents need a transaction or a design that keeps them in one document. |
| Schemaless means no schema? | Validation | Collections do not force a schema, but you can add a $jsonSchema validator. In practice the application code is the schema, so versioning documents matters. |
| What do upserts do? | Write semantics | An update with upsert: true inserts a new document when no document matches the filter. Without a unique index, two concurrent upserts can insert duplicates. |
| What is a TTL index? | Expiry | An index on a date field with expireAfterSeconds; a background task deletes expired documents, so removal is not instant. |
| When would you use a capped collection or a time series collection? | Specialized collections | Capped for fixed-size, insertion-ordered logs that overwrite the oldest entries. Time series for measurements over time, with storage optimized by time and a metadata field. |
Data modeling: embed or reference
This is the heart of most MongoDB interviews. The rule interviewers want to hear: data that is read together should be stored together, as long as it stays bounded. Then name the pattern.
| Situation | Choice | Why |
|---|---|---|
| A user's two or three addresses | Embed an array | One-to-few, always read with the user, small and bounded. |
| A product's reviews, possibly thousands | Separate reviews collection with productId; embed the latest few on the product (subset pattern) | Keeps the product document small while the page shows recent reviews without a second query. |
| An order that shows the customer's name and address at the time of purchase | Copy those fields into the order (extended reference) | The order must keep historical values even if the customer later moves. |
| Sensor readings every second | Bucket pattern or a time series collection | One document per sensor per hour instead of 3,600 tiny documents; fewer index entries. |
| A counter displayed on every page view | Computed pattern | Store the precomputed total and update it on write instead of counting at read time. |
| Documents with an old and a new shape | Schema versioning | A schemaVersion field lets the code read both shapes and migrate lazily. |
| Many-to-many, such as students and courses | Arrays of references on one or both sides | Pick the side that is queried most; keep arrays bounded. |
- Why is an unbounded array an anti-pattern? The document grows without limit, rewrites get heavier, multikey indexes balloon, and eventually the 16 MB cap is hit.
- When is $lookup acceptable? For occasional reports and admin views. If a hot API path needs a join on every request, the model probably should embed or copy the data.
- How do you keep copied data consistent? Decide whether staleness is acceptable. If not, update copies in the same transaction or through a change stream consumer, and say how often the source really changes.
- How would you model a comment thread with replies? A comments collection with postId and parentId (or an ancestors array for subtree queries), not one giant post document.
Indexes and explain plans
- What is the ESR rule? Order compound index fields as Equality first, then Sort, then Range. That lets the index both narrow and deliver results in order without an in-memory sort.
- What is a multikey index? An index on an array field gets one entry per element. A compound index can include at most one array field per document, otherwise inserts fail.
- What does explain("executionStats") tell you? The winning plan (IXSCAN or COLLSCAN, SORT stages) and three numbers: keys examined, documents examined and documents returned. Ideally all three are close.
- What is a covered query? One answered from the index alone: all filtered and returned fields are in the index, and _id is excluded from the projection unless it is indexed with them.
- Partial, sparse, unique, hashed, text, 2dsphere, wildcard: name a use for each. Partial for indexing only active rows; sparse for skipping missing fields; unique for emails; hashed for even shard distribution; text for basic keyword search; 2dsphere for geospatial queries; wildcard for unpredictable attribute fields.
- How do you add an index without hurting production? Index builds no longer hold an exclusive lock for their whole run, but they still use resources; build during quieter periods and check memory, since indexes should fit in RAM with the working set.
- How many indexes are too many? Every index costs on each insert and update and uses cache. Remove ones with no use according to $indexStats.
// Open orders for one customer, newest first, above a minimum total
db.orders.find(
{ customerId: 42, status: "open", total: { $gte: 100 } }
).sort({ createdAt: -1 });
// Equality fields, then the sort field, then the range field
db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1, total: 1 });
db.orders.find(
{ customerId: 42, status: "open", total: { $gte: 100 } }
).sort({ createdAt: -1 }).explain("executionStats");
// Look for IXSCAN with no SORT stage, and totalDocsExamined close to nReturnedAggregation pipeline questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why put $match first? | Pipeline order | An early $match can use an index and shrinks every later stage. A $match after $group or $project usually cannot use an index. |
| What does $unwind do, and what is the risk? | Array handling | It emits one document per array element. On big arrays it multiplies documents; filter before unwinding and consider preserveNullAndEmptyArrays. |
| How do you join two collections? | $lookup | $lookup with localField and foreignField, or a sub-pipeline for conditions. Index the foreign field, or each input document triggers a scan. |
| How do you compute several summaries in one pass? | $facet | $facet runs sub-pipelines on the same input, for example counts by status and a price histogram for a search page. |
| What happens when a stage runs out of memory? | Limits | Blocking stages such as $group and $sort have a memory limit per stage; allowDiskUse lets them spill to disk at a speed cost. |
| Aggregation or doing it in application code? | Judgment | Aggregate on the server when it shrinks data before sending it over the network; move it out when the logic is complex and the input is small. |
db.orders.aggregate([
{ $match: {
status: "paid",
createdAt: { $gte: ISODate("2026-11-01"), $lt: ISODate("2026-12-01") }
} },
{ $unwind: "$items" },
{ $group: {
_id: "$items.category",
revenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } },
orders: { $addToSet: "$_id" }
} },
{ $project: { _id: 0, category: "$_id", revenue: 1, orderCount: { $size: "$orders" } } },
{ $sort: { revenue: -1 } },
{ $limit: 5 }
]);A follow-up that catches people: $addToSet keeps every order ID in memory per category, which is fine for one month but not for years of data. A cheaper count groups by category and order first, then groups again by category.
Transactions, replica sets and consistency
- Does MongoDB support ACID transactions? Yes, multi-document transactions on replica sets and sharded clusters. They cost more than single-document writes and have time limits, so the first answer should still be a model that keeps related changes in one document.
- What should the client do when a transaction fails? Retry the whole transaction on TransientTransactionError and retry the commit on UnknownTransactionCommitResult. The drivers' withTransaction helper does this.
- What is a replica set? One primary that takes writes and secondaries that copy its oplog. If the primary fails, the members hold an election and a secondary becomes primary, usually within seconds.
- Why avoid arbiters where you can? An arbiter votes but holds no data. With a primary, a secondary and an arbiter, losing the secondary leaves one data-bearing member, and majority writes cannot be acknowledged.
- What is the oplog window? How far back the oplog reaches in time. A secondary that falls behind further than that cannot catch up and needs a full resync.
- What are read preferences? primary, primaryPreferred, secondary, secondaryPreferred and nearest. Reading from secondaries spreads load but returns possibly stale data.
| Setting | Meaning | Trade-off |
|---|---|---|
| w: 1 | Acknowledged by the primary only | Fast; a write can be rolled back if the primary fails before replicating it. |
| w: "majority" | Acknowledged by a majority of voting members | Survives a failover; higher latency. Recent versions use it as the default in most deployments. |
| j: true | Written to the on-disk journal before acknowledging | Durability on the acknowledging members against a crash. |
| readConcern "local" | Latest data on the node, possibly not yet majority-committed | Fast; may read data that is later rolled back. |
| readConcern "majority" | Only data acknowledged by a majority | Never rolled back; may lag slightly. |
| readConcern "linearizable" | Reflects all majority writes completed before the read | Primary only, slowest; for rare must-be-current reads. |
| Causally consistent session | Your reads see your own earlier writes, even on secondaries | Use with majority read and write concern. |
Sharding and shard keys
- How does a sharded cluster route a query? Clients talk to mongos routers, which use metadata from the config servers to send the query to the shards that own the relevant ranges. Queries that include the shard key are targeted; others go to every shard (scatter-gather).
- What makes a good shard key? High cardinality, writes spread evenly, and present in most queries. A compound key such as { tenantId: 1, createdAt: 1 } often balances these.
- Why is a monotonically increasing key, like an ObjectId or a timestamp, a problem? Every new document lands in the highest range, so one shard takes all inserts. Hashed sharding fixes the distribution but makes range queries scatter.
- Hashed versus ranged sharding? Hashed spreads writes evenly; ranged keeps nearby keys together for efficient range scans. Choose by the dominant query.
- What is a jumbo chunk? A range that cannot be split because too many documents share the same shard key value, so the balancer cannot move it. Low-cardinality keys cause it.
- Can you change a shard key? Newer versions can reshard a collection online or refine a key by adding suffix fields, but it is expensive. Interviewers want to hear that you choose carefully up front.
- What are zones for? Pinning ranges of the shard key to particular shards, for example keeping EU customers' data on EU hardware.
Scenario questions
| Scenario | Likely cause | What you would check |
|---|---|---|
| A list endpoint slowed down as the collection grew. | COLLSCAN or an in-memory SORT | explain("executionStats") and the slow query log; add an ESR-ordered index. |
| Writes started failing on one popular document. | Unbounded array near 16 MB | Document size with $bsonSize; move the array into its own collection. |
| One shard has twice the disk and CPU of the others. | Hot or monotonic shard key | Chunk distribution with sh.status(); consider hashing or resharding. |
| Users sometimes do not see their own update. | Secondary reads | Read preference and read concern; use causal consistency or read from the primary after writes. |
| Writes were "lost" after a failover. | w: 1 and a rollback | Rollback files on the old primary; switch critical writes to w: "majority". |
Fictional example
- Interviewer
- Learners enroll in courses, each course has up to 200 lessons, and we track which lessons each learner finished. How would you model it in MongoDB?
- Candidate
- I would start from the screens. The course page shows the course with its lesson titles, so I would embed a lessons array with id, title and duration in the course document; 200 small entries is bounded. Lesson content can be large, so it lives in a lessons collection fetched one at a time. Progress is per learner per course and changes constantly, so it gets its own collection with one document per enrollment: learnerId, courseId, a completedLessonIds array that cannot exceed the lesson count, and a percent field I update on each completion, which is the computed pattern. A unique compound index on learnerId and courseId serves the dashboard and stops duplicate enrollments. Marking a lesson done is one update with $addToSet, atomic on a single document, so no transaction is needed. If we ever shard progress, learnerId is a natural key, since every query includes it.
Two-week MongoDB practice plan
- Days 1 to 3: model three apps (a blog, a store, a sensor feed) on paper, then justify every embed and every reference in one sentence.
- Days 4 to 6: load a few hundred thousand generated documents locally, write ten queries and read explain output for each before and after adding indexes.
- Days 7 to 9: write five aggregation pipelines with $match, $group, $unwind, $lookup and $facet, and predict the output before running them.
- Days 10 to 12: start a three-member replica set, step down the primary during writes, and compare w: 1 with w: "majority".
- Days 13 and 14: practice the shard key discussion and the scenario table out loud, two minutes each.
For the relational side of a SQL versus NoSQL discussion, see PostgreSQL interview questions, which also covers JSONB as a middle path, and SQL vs NoSQL in system design. Caching in front of MongoDB is covered in Redis interview questions. Many MongoDB backends serve a GraphQL API, which brings its own N+1 problem: see GraphQL interview questions.
Data modeling answers improve quickly with replay. When you run a mock round, Natively, an AI interview assistant for Mac and Windows, writes a transcript on your computer, so you can see whether you justified each embed or skipped straight to a schema. In practice it can read a modeling prompt or an explain output from a screenshot and suggest an approach, and with Pro or the free trial it can take the résumé and job description you add into account. The transcript and notes are there to review later.
Questions people ask
What MongoDB questions are asked in interviews?
Expect document modeling (embed versus reference and patterns such as bucket and subset), compound indexes and explain plans, the aggregation pipeline, transactions, replica sets, read and write concerns, and choosing a shard key.
When should you embed and when should you reference in MongoDB?
Embed data that is read together with its parent and stays bounded, such as a few addresses. Reference data that grows without limit, is shared by many parents or changes on its own schedule, such as reviews or comments.
What is a good shard key in MongoDB?
One with high cardinality, an even spread of writes and presence in most queries so they can be targeted. Avoid monotonically increasing keys such as timestamps on their own, which send every insert to one shard.
What is write concern majority in MongoDB?
The write is acknowledged only after a majority of voting replica set members have it, so it survives the primary failing. It costs some latency compared with w: 1, which can lose writes in a failover.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
