PrepStack › Databases › MongoDB
MongoDB interview cheat sheet
Document model, queries, schema design, indexes, aggregation, replication and sharding
MongoDB interviews check whether you can design for the access pattern instead of normalising by habit. Expect questions on the document model and BSON, CRUD and update operators, embed vs reference, compound indexes and the ESR rule, reading explain(), the aggregation pipeline, and how replica sets, sharding, transactions and read/write concerns behave under failure. Read the 15-minute revision first; the plain-JS snippets simulate server behaviour, while mongosh snippets show the real syntax.
15-minute revision
- A document is a BSON object (max 16 MB). Documents live in collections, collections in databases. No fixed schema unless you add schema validation.
- Every document needs a unique, immutable
_id(auto-indexed). The default is a 12-byte ObjectId: 4-byte seconds timestamp + 5-byte random + 3-byte counter. - Writes to a single document are atomic, including embedded arrays and sub-documents. Multi-document ACID transactions exist (replica sets 4.0, sharded 4.2) but cost more.
- Model for reads: data that is read together is stored together. Embed one-to-few and bounded data; reference unbounded or independently accessed data.
- Update with operators (
$set,$inc,$push,$addToSet,$pull). A plain object replaces the whole document (replaceOne).upsert: trueinserts when nothing matches. - Array queries:
{tags: 'db'}means contains. Several conditions on one array field may match different elements; use$elemMatchto force one element. - Compound index field order follows ESR: Equality fields, then Sort fields, then Range fields. A compound index also serves its prefixes.
- Index an array field and it becomes multikey (one key per element). A compound index can include at most one array field per document.
- Special indexes: TTL (auto-delete by date), partial (only matching docs), unique, text, wildcard (
$), hashed, 2dsphere**. explain('executionStats'): look forIXSCANvsCOLLSCAN, an in-memorySORTstage, and the ratio oftotalKeysExamined/totalDocsExaminedtonReturned(ideal ≈ 1:1:1).- Aggregation is a pipeline of stages. Put
$match(and$sort+$limit) first so they can use indexes;$lookupis a left outer join;$facetruns several sub-pipelines on one input. - Replica set = one primary that takes writes + secondaries that replay its oplog. If the primary is lost, a majority vote elects a new one, typically within about 10–12 seconds.
- Default write concern is
w: 'majority'(since 5.0); default read concern islocal.majorityread + write concerns protect against rollback after failover. - Sharding splits a collection by shard key into ranges (chunks) across shards;
mongosroutes queries; the balancer moves ranges. A monotonically increasing ranged key creates a hot shard. - Change streams let apps subscribe to inserts/updates/deletes; they read the oplog and can resume from a resume token.
- Current releases (Dec 2026): 9.0 (Sept 2026) is the current major; 8.0 (2024) is the previous major still widely deployed. Avoid MongoDB for heavily relational, join-heavy or OLAP-style workloads.
Foundations
Document model & MongoDB vs SQL
MongoDB stores rich JSON-like documents in collections, so one read can return a whole business object without joins.
- A document is a set of field/value pairs. Values can be scalars, arrays or embedded documents, so an order can hold its line items directly.
- A collection groups documents. It has no enforced shape by default (flexible schema), but documents in one collection should usually share a shape.
- This removes much of the object-relational mapping gap: the stored document looks like the object in your code.
- Scaling story: replica sets for high availability, sharding for horizontal scale. Both are built in.
- Flexible does not mean schemaless in practice. You still design the schema; you just design it around queries, not normal forms.
Interview questions
- What is MongoDB and when is it a good fit?
- Difference between a document database and a relational database?
- How do you do a JOIN in MongoDB?
BSON, _id & ObjectId
BSON is a binary, typed, length-prefixed JSON; _id is the unique primary key, and ObjectId encodes a creation timestamp.
- BSON adds types JSON lacks:
ObjectId,Date,Int32/Int64(Long),Double,Decimal128,Binary,Timestamp, regex,MinKey/MaxKey. - Each element stores its type byte and length, so the server can skip fields without parsing them. The cost is a little extra space for field names in every document.
- Limits: a document is at most 16 MB and nesting is limited to 100 levels. Use GridFS for larger files.
_idis required, unique (it always has a unique index) and immutable. It can be any type except an array. If you omit it, the driver generates an ObjectId.- ObjectId is 12 bytes: a 4-byte timestamp (seconds), a 5-byte random value per process, and a 3-byte counter that starts at a random value.
- Because the timestamp comes first, ObjectIds are roughly increasing. You can sort by
_idto approximate insertion order and callgetTimestamp()to see creation time.
Interview questions
- What is the structure of an ObjectId?
- Why does MongoDB use BSON instead of JSON?
- What is the maximum document size and how do you store bigger data?
CRUD & querying
CRUD & projection
Use insertOne/Many, find/findOne, updateOne/Many, replaceOne and deleteOne/Many; project only the fields you need.
- Create:
insertOne(doc),insertMany(docs, { ordered }). Withordered: falsethe server keeps going after a failed document. - Read:
find(filter, projection)returns a cursor (batched, lazily fetched);findOnereturns the first match ornull. Chain.sort(),.skip(),.limit(). - Update:
updateOne/updateManytake update operators;replaceOneswaps the whole document (keeps_id).findOneAndUpdatereturns the document before or after the change. - Delete:
deleteOne/deleteMany.deleteMany({})empties the collection but keeps its indexes;drop()removes everything. - Projection picks fields:
{ name: 1, email: 1 }(inclusion) or{ password: 0 }(exclusion). You cannot mix the two styles, except to exclude_id. bulkWritebatches mixed inserts, updates and deletes into fewer round trips.
Interview questions
- Difference between
updateOne,replaceOneandfindOneAndUpdate? - Why should you avoid large
skip()values for pagination? - What is a cursor in MongoDB?
Query operators & arrays
Filters are documents of field conditions; dot notation reaches into sub-documents, and arrays match if any element matches.
- Comparison:
$eq $ne $gt $gte $lt $lte $in $nin. Logical:$and $or $nor $not. Fields in one filter are implicitly ANDed. - Element:
$exists(field present) and$type(BSON type).{ x: null }matches documents wherexis null or missing. - Dot notation queries nested fields and array positions:
'address.city','items.sku','items.0.sku'. It must be quoted. - Arrays:
{ tags: 'db' }matches if the array contains'db'.$allrequires all listed values;$sizechecks exact length. $elemMatchrequires one element to satisfy every condition. Without it, each condition may match a different element.- Others:
$regex(anchored prefix regexes like/^abc/can use an index),$expr(compare two fields),$text(needs a text index).
Interview questions
- When do you need
$elemMatch? - What does
{ field: null }match? - How do you compare two fields of the same document?
Update operators & upsert
Update operators change parts of a document atomically; upsert inserts a new document when the filter matches nothing.
- Fields:
$set,$unset,$inc,$mul,$min,$max,$rename,$currentDate,$setOnInsert(only applied when an upsert inserts). - Arrays:
$push(append; with$each,$slice,$sort,$position),$addToSet(append if absent),$pull(remove matching),$pop(first/last). - Positional updates:
$updates the first element matched by the filter;$[]updates every element;$[name]witharrayFiltersupdates matching elements. upsert: truebuilds the new document from the filter's equality fields plus the update. Without a unique index on the filter fields, two racing upserts can insert duplicates.- Each update on one document is atomic, so
$inccounters are safe under concurrency without a transaction. - Updates can also be an aggregation pipeline (
[{ $set: { total: { $sum: '$items.price' } } }]) to compute from other fields. Since 8.0,updateOneaccepts asortto pick which match is updated.
Interview questions
- Difference between
$pushand$addToSet? - What is an upsert and what is the race condition with it?
- How do you implement a safe counter or inventory decrement?
Schema design
Embed vs reference
Embed what you read together and what stays bounded; reference what grows without limit or is shared and updated independently.
- Embed for one-to-one and one-to-few (addresses on a user). One read, one atomic write, no join.
- Reference when the child list is unbounded, the child is accessed on its own, or the same data is shared by many parents and changes often.
- One-to-many: store an array of child ids in the parent (e.g. product → part ids) when the list is in the hundreds.
- One-to-squillions: store the parent id in each child (log lines → host). Never keep a growing array of millions of ids.
- Many-to-many: arrays of ids on one or both sides, chosen by which side you query from.
- Duplicating some data (denormalising) is fine when reads far outnumber updates. Decide how stale a copy may be and how it gets refreshed.
Interview questions
- How do you decide between embedding and referencing?
- How would you model a blog with posts and comments?
- What is the one-to-squillions pattern?
Schema design patterns
Named patterns (subset, bucket, extended reference, computed, outlier and more) solve recurring size and read-cost problems.
- Subset: keep only the most-used part of a big list in the main document (latest 10 reviews) and the rest in another collection. Keeps the working set in RAM.
- Bucket: group many small time-ordered items into one document per period or per N items (one document per sensor per hour). Fewer documents, smaller indexes, easy pre-aggregates.
- Extended reference: copy the few fields you always show (customer name, city) into the referencing document to avoid a
$lookup. - Computed: store derived values (totals, counts, ratings) at write time when reads far outnumber writes.
- Outlier: design for the normal case, and flag the rare huge one (
hasOverflow: true) whose extra data spills into overflow documents. - Also asked: attribute (array of
{k, v}pairs to index many sparse fields), polymorphic (different shapes in one collection with atypefield), schema versioning (schemaVersionfield for gradual migration). For time-series, prefer built-in time series collections, which bucket automatically.
Interview questions
- Explain the bucket pattern and when you would use it.
- What is the extended reference pattern?
- A product has normally 50 reviews but a few have 100,000. How do you model it?
- What is the computed pattern and its risk?
Schema validation
Collections can enforce rules with $jsonSchema (or query operators); the level and action decide what is checked and what happens on failure.
- Set a
validatoratcreateCollectionor later withcollMod. Most teams use$jsonSchema(required fields,bsonType, enums, min/max, patterns). - validationLevel:
strict(default; checks all inserts and updates) ormoderate(checks inserts and updates to documents that are already valid).offdisables it. - validationAction:
error(default; reject the write) orwarn(allow it and log a warning). Usewarnwhile rolling out rules on existing data. additionalProperties: falseforbids unknown fields; remember to list_id.- Users with the right privilege can skip checks with
bypassDocumentValidation, e.g. for migrations. - Validation does not check referential integrity and does not replace application-level validation; it is a safety net at the data layer.
Interview questions
- How do you enforce a schema in MongoDB?
- Difference between
strictandmoderatevalidation levels? - What happens with
validationAction: 'warn'?
Indexes & aggregation
Index types
Indexes are B-trees of field values pointing to documents; MongoDB adds multikey, text, TTL, partial, wildcard, hashed and geo variants.
- Without a usable index, a query does a collection scan (
COLLSCAN). With one, it walks a B-tree (IXSCAN), then fetches documents (FETCH) if needed. - Single-field and compound indexes; direction matters only for multi-field sorts. A compound index serves queries on its prefixes.
- Multikey: created automatically when an indexed field holds an array (one key per element). A compound index cannot index two array fields in the same document.
- Unique (also on compound keys), partial (
partialFilterExpression, only docs that match), sparse (older; only docs having the field), TTL (expireAfterSecondson a date field). - Text index (one per collection) for basic keyword search with
$text; wildcard ({ '$': 1 }or'attrs.$') for unpredictable field names; hashed for hash sharding; 2dsphere for geo. - Every index costs RAM and slows writes. Limit: 64 indexes per collection. Builds do not block reads and writes for their whole duration (since 4.2).
Interview questions
- What is a multikey index?
- Difference between a sparse and a partial index?
- How does a TTL index work?
Compound indexes & the ESR rule
Order compound index fields Equality → Sort → Range so the index both narrows the scan and returns results already sorted.
- A compound index is sorted by the first field, then the second within it, and so on, like a phone book (last name, first name).
- Prefix rule: index
{ a: 1, b: 1, c: 1 }serves queries ona,a+b,a+b+c, but not onbalone orcalone. - Equality first: exact matches narrow the scan to one contiguous slice.
- Sort next: inside that slice the entries are already in sort order, so no in-memory
SORTstage. - Range last: range bounds (
$gt,$lt,$inwith sort,$regex) on a field placed before the sort field would break the ordering. - Sort direction:
{ a: 1, b: -1 }supports sorts{ a: 1, b: -1 }and its full reverse{ a: -1, b: 1 }, not{ a: 1, b: 1 }.
Interview questions
- What is the ESR rule?
- You have index
{ a: 1, b: 1, c: 1 }. Which queries use it? - What is a covered query?
- Why does
{ a: 1, b: -1 }not support.sort({ a: 1, b: 1 })?
explain() & query performance
explain() shows the winning plan and how much work it did; compare keys and documents examined with documents returned.
- Verbosity:
queryPlanner(chosen plan only),executionStats(runs it and reports work),allPlansExecution(also the trial runs of rejected plans). - Stages to recognise:
COLLSCAN(full scan),IXSCAN(index walk),FETCH(load documents),SORT(in-memory sort),PROJECTION_COVERED(no fetch),SHARD_MERGE(sharded). - Health ratio:
nReturned≈totalKeysExamined≈totalDocsExaminedis ideal. Many more docs than returned means the index is not selective enough. - The plan cache: for a new query shape, candidate plans race for a short trial; the winner is cached and re-evaluated if it performs poorly.
- Operational tools: the database profiler (
db.setProfilingLevel(1, { slowms: 100 })), slow-query log lines,$indexStats,currentOp, Atlas Performance Advisor. - 8.0 added an express path that skips normal planning for simple
_idequality lookups and query settings (setQuerySettings) to pin an index for a query shape without code changes.
Interview questions
- How do you find and fix a slow query in MongoDB?
- Difference between
queryPlannerandexecutionStatsverbosity? - How does MongoDB pick an index when several qualify?
Aggregation pipeline
Documents flow through an ordered list of stages; each stage transforms the stream and passes it on.
$matchfilters (like WHERE),$project/$set/$unsetreshape,$groupaggregates by_idwith accumulators ($sum,$avg,$min,$max,$push,$addToSet,$first).$sort,$limit,$skip,$count;$unwindemits one document per array element (preserveNullAndEmptyArrayskeeps empty ones).$lookupis a left outer join to another collection (simplelocalField/foreignFieldor a sub-pipelinewithlet). Results come back as an array.$facetruns several sub-pipelines on the same input and returns one document (e.g. results + counts + price buckets for a search page).- Output:
$outreplaces a collection;$mergeupserts into one, which is how you build on-demand materialised views. - Others worth knowing:
$bucket,$sortByCount,$unionWith,$setWindowFields(running totals, ranks),$graphLookup(recursive).
Interview questions
- What is the aggregation pipeline?
- Difference between
$projectand$group? - What does
$unwinddo and when is it a problem? - Difference between
$outand$merge?
$lookup, $facet & pipeline optimisation
Filter and limit early, keep joins indexed and small, and know the optimiser's reordering and memory rules.
- Only the first stages (
$match,$sort, and$geoNear/$searchwhich must be first) can use indexes on the source collection. Once data is reshaped, indexes no longer apply. - The optimiser moves
$matchahead of stages it does not depend on, merges adjacent$matches, coalesces$sort+$limitinto a top-k sort, and combines$lookup+$unwind. $lookupruns one lookup per input document, so index theforeignFieldand reduce input first. Sharded collections can be thefromtarget since 5.1.- Memory: each blocking stage (
$group,$sort,$bucket) has a 100 MB limit; it spills to disk whenallowDiskUseis on (the default since 6.0). 9.0 also adds a per-operation memory limit for queries. $facetsub-pipelines cannot use indexes, and its single output document is still bound by 16 MB. Put the shared$matchbefore$facet.- Prefer schema changes (embedding, computed fields,
$merge-built summary collections) over a heavy pipeline that runs on every request.
Interview questions
- How do you optimise an aggregation pipeline?
- Is
$lookupas good as a SQL join? - What happens when a
$groupexceeds memory? - When would you use
$facet?
Consistency, replication & scaling
Transactions
Single-document writes are always atomic; multi-document ACID transactions exist for the cases a good schema cannot avoid.
- Multi-document transactions: replica sets since 4.0, sharded clusters since 4.2. They give snapshot isolation and all-or-nothing commit across documents and collections.
- They run in a session. Use the driver's
withTransactionhelper; it retries onTransientTransactionErrorand retries the commit onUnknownTransactionCommitResult. - Default maximum runtime is 60 seconds (
transactionLifetimeLimitSeconds); longer ones are aborted. Keep them short and touch few documents. - Conflicts: if two transactions write the same document, one gets a write conflict and must retry. A transaction does not block plain reads.
- Use them for things like money transfers between two accounts, or order + inventory + ledger updates that must be consistent together.
- First ask whether embedding makes the change a single-document update; that is cheaper and naturally atomic.
Interview questions
- Does MongoDB support ACID transactions?
- When do you actually need a multi-document transaction?
- What are the limitations of transactions?
- What is
TransientTransactionError?
Read/write concerns & read preference
Write concern says how many members must confirm a write; read concern says how durable the data you read must be; read preference says which member to read from.
- Write concern
w:0(fire and forget),1(primary only),'majority'(default since 5.0), or a number.j: truewaits for the journal;wtimeoutbounds the wait. - A
w: 1write acknowledged by a primary that dies before replicating can be rolled back when it rejoins.majoritywrites survive failover. - Read concern:
local(default; latest on that node, may be rolled back),available(like local, for sharded edge cases),majority(only majority-committed data),linearizable(primary only, reflects all prior majority writes),snapshot(transactions and point-in-time reads). - Read preference:
primary(default),primaryPreferred,secondary,secondaryPreferred,nearest; can add tag sets andmaxStalenessSeconds(minimum 90). - Reading from secondaries gives eventually consistent data. Use causally consistent sessions with majority concerns to read your own writes on a secondary.
- Since 8.0,
majoritywrites are acknowledged once a majority has written the oplog entry, not necessarily applied it, which lowers latency.
Interview questions
- Difference between write concern
w: 1andw: 'majority'? - What is read concern
majorityvslocal? - When would you read from secondaries?
- How do you guarantee read-your-own-writes in a replica set?
Replica sets, elections & oplog
A replica set is a group of mongod nodes with one primary and copies kept in sync through the oplog, giving automatic failover.
- Primary takes all writes and records them in the oplog (
local.oplog.rs, a capped collection). Secondaries pull the oplog and apply it, in parallel batches. - Oplog entries are idempotent (e.g.
$incis recorded as the resulting$set), so replaying them is safe. - Members heartbeat each other every 2 seconds. If the primary is unreachable for
electionTimeoutMillis(default 10 s), a secondary calls an election; the candidate needs votes from a majority of voting members. The protocol is Raft-like. - Use an odd number of voting members (3 or 5) across failure zones. Max 50 members, max 7 voting.
- Special members: arbiter (votes, no data; discouraged), hidden (no client reads, good for backups/analytics), delayed (lags on purpose to recover from mistakes),
priority: 0(never becomes primary). - The oplog window (hours of history) decides how long a member can be down and still catch up without a full initial sync, and how far back change streams can resume.
Interview questions
- What is a replica set and why use one?
- How does election work in MongoDB?
- What is the oplog?
- Why is an odd number of members recommended?
Real-time, search & choosing MongoDB
Change streams
Change streams push insert/update/delete events to your app in real time, built on the oplog and resumable after failures.
- Open with
watch()on a collection, database or the whole deployment. Requires a replica set or sharded cluster (they read the oplog). - Each event has an
operationType(insert,update,replace,delete,invalidate, …), thedocumentKey, and for updates anupdateDescriptionwith changed fields. fullDocument: 'updateLookup'fetches the current document for updates. For exact before/after values, enable pre- and post-images on the collection (6.0+).- Every event carries a resume token (
_id). Store it after processing; on restart passresumeAfter/startAfterto continue without missing events, as long as it is still in the oplog window. - You can filter and reshape events with a pipeline (
$match,$project) so the server sends only what you need. - Uses: cache invalidation, syncing to search or analytics, event-driven microservices, notifications. For delivery to external systems, the Kafka connector or Atlas Triggers build on the same feature.
Interview questions
- What are change streams?
- How do you avoid losing events if your consumer crashes?
- Change streams vs polling the database?
Atlas Search & Vector Search
Atlas Search adds Lucene full-text search and Vector Search adds semantic similarity search, both as aggregation stages next to your data.
- Atlas Search runs a Lucene-based
mongotprocess besidemongod, kept in sync from the oplog. Query it with the$search(or$searchMeta) stage, which must be first in the pipeline. - It offers what
$textlacks: analyzers per language, fuzzy matching (typos), autocomplete, relevance scoring and boosting, highlighting and facets. - Vector Search indexes embedding arrays and runs approximate nearest-neighbour (HNSW) search via
$vectorSearchwithqueryVector,numCandidates,limitand an optional pre-filter. - Typical use: RAG for LLM apps; store chunks, metadata and embeddings in one document, then combine vector similarity with normal filters.
- Search indexes are separate from normal B-tree indexes and are eventually consistent (a short lag after writes). They are also available for self-managed deployments through
mongot. - Self-hosted alternative: sync to Elasticsearch/OpenSearch with change streams; Atlas Search avoids that extra pipeline.
Interview questions
- Difference between a
$textindex and Atlas Search? - How would you build a RAG feature on MongoDB?
- Why must
$searchand$vectorSearchbe the first stage?
When (not) to use MongoDB & versions
Great for aggregate-shaped, evolving, high-scale operational data; a poor fit for join-heavy relational models and big ad-hoc analytics.
- Good fit: catalogs, content and user profiles, IoT and event data (time series), mobile/real-time apps, multi-tenant SaaS, AI apps that need operational data and vectors together.
- Poor fit: highly relational data with many-to-many joins in most queries, heavy cross-entity constraints (foreign keys, complex checks), OLAP reporting with ad-hoc joins over large datasets, and small teams with simple relational data already served well by PostgreSQL.
- PostgreSQL
JSONBcovers some document needs inside a relational database; MongoDB wins on native horizontal scaling and document-first tooling. - 8.0 (Oct 2024): major performance work,
_idexpress path, query settings,updateOnesort, config shard,moveCollection/unshardCollection, Queryable Encryption range queries. - 9.0 (released Sept 28, 2026) is the current major. It adds a per-operation query memory limit, query stats on by default, and un-deprecates server-side JS (
$function,$accumulator,$where). Minor releases (8.2, 8.3 …) ship to Atlas first; from 9.0 self-managed users get an annual x.5 Feature Update release. - Licensing: Community Server is under SSPL (not OSI open source); Enterprise Advanced and Atlas are commercial.
Interview questions
- When would you not use MongoDB?
- MongoDB vs PostgreSQL: how do you choose?
- What changed in recent MongoDB versions?
- Is MongoDB open source?