54 MongoDB interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
MongoDB is a document-oriented NoSQL database that stores flexible JSON-like records, which suits data whose shape changes or nests naturally. The questions cover the document model and schema design, CRUD and querying, indexes, the aggregation pipeline, transactions and consistency, replication and the oplog, sharding and shard keys, change streams, and security.
and 7 more topics.
MongoDB is a document database: instead of splitting data into many tables, it stores a whole "chunk" of related data in one document (like a JSON object) inside a collection. Under the hood, documents are stored as BSON. When to choose: - Data has a…
- Document: a data unit stored as BSON, like a JSON object (key-value pairs). - Collection: a group of documents, similar to a "table" in RDBMS — but it does not require every document to share the same shape. - Database: a namespace holding many…
Simply put: JSON is text for humans and machines to exchange data; BSON (Binary JSON) is the binary form MongoDB uses to store documents — optimized for fast traversal and parsing, not for compactness. BSON stores a length and a type byte for each field,…
Four basic CRUD operations on a collection: - findOne: returns exactly one matching document (or null). - find: returns a cursor (a pointer) to many matching documents. - insertOne: inserts a new document. - updateOne: updates the first document matching the filter. Example: Note: always…
The core question: should child data live inside the parent (embed) or in a separate collection that you point to (reference)? Embed when: - Child data belongs entirely to the parent and is usually read together. - The count is small and bounded. - It…
Each MongoDB document is capped at 16MB. Design consequences: - Don't embed indefinitely: arrays that can grow forever — comments, events, logs, transactions — should not keep piling into a parent document; you will eventually hit the 16MB ceiling. - Use References or the Bucket…
Like a book's index: it lets MongoDB jump straight to the documents it needs instead of scanning the whole collection. Benefits: - Faster lookups (avoids collection scans). - Efficient sorting (sort). Trade-offs: - Extra storage (disk and RAM). - Slower writes, since every insert/update/delete must…
Like a phone book sorted by "last name then first name", field order in a compound index decides which queries can use it. The practical rule is ESR (Equality → Sort → Range): - Equality first: exact-match filter fields (e.g. tenantId, status). - Sort next:…
When you index a field containing an array, MongoDB automatically creates a multikey index: it indexes each element of the array rather than the whole array, so finding documents containing a given element is fast. Example: Note: with a compound multikey index, each document may…
A TTL (Time-To-Live) index automatically deletes documents after a set time, based on a Date field. Good for: temporary data like sessions, tokens/OTPs, verification links, short-lived logs, cache. Example: Note: deletion is not perfectly real-time — a background process runs periodically (about every 60 seconds)…
ObjectId is the default type for the id field in MongoDB. It is 12 bytes, generated to be nearly unique even across many machines, and embeds a timestamp, so you can derive an approximate creation time (often saving a separate createdAt column if you only…
$lookup works like a LEFT OUTER JOIN in SQL: for each document entering the stage, it finds the matching documents in another collection and attaches them as an array. Documents with no match are kept, with an empty array. Each user comes out with an…
Yes. A write to a single document is always atomic, even when the document has many fields and nested arrays. Since version 4.0, MongoDB also supports multi-document ACID transactions (on replica sets), extended to sharded clusters since 4.2. But keep in mind: - MongoDB is…
Sharding solves the physical limit of a single server by splitting data across multiple servers (horizontal scaling). Use it when a collection is too large for one disk, or read/write traffic exceeds the CPU/RAM of your most powerful replica-set machine. Note: choosing the shard key…
Write concern is the level of "write guarantee" the client asks MongoDB to confirm before treating a write as successful. Common levels: - w: 0: no acknowledgement at all; the write is considered done once sent. Fastest, but you never learn about write errors. -…
Read preference decides which node in the replica set serves the client's read queries. Common options: - primary (default): all reads go to the Primary → always the latest data (strong consistency). - secondaryPreferred: prefers Secondaries to offload the Primary; good for reporting/dashboards that tolerate…
The find() method does not load all results into RAM at once; it returns a cursor — a pointer to the result set. As you iterate, MongoDB fetches data in small batches. So when building a list API, don't call toArray() on a large collection:…
The oplog (Operations Log) is a special capped collection that records every data-changing operation (insert/update/delete) on the Primary. Secondaries "tail" this oplog and replay it to stay in sync with the Primary — this is the replication mechanism. Operational note: the oplog has a bounded…
The schema versioning pattern adds a field such as schemaVersion to each document, so the code knows which structure a document is in when the data shape changes over time. Example: v1 stores name as one string, v2 splits it into firstName and lastName. Old…
A shard key is the field (or group of fields) used to distribute data across shards. Choose well from the start because changing it later is expensive: 4.4 added refineCollectionShardKey (append a suffix field to the current key), and 5.0 added reshardCollection (switch to a…
Both match multiple conditions, but they differ: - $in: matches multiple values on the same field. Easily uses a single index, with excellent performance. - $or: usually combines conditions across different fields. MongoDB plans each branch of the $or independently, each branch picking its own…
By default, reading from the Primary gives you "strong consistency" (always the latest). But if readPreference is set to secondary, you may get stale data. Why: the Primary writes the data and writes an oplog entry in the same operation. Secondaries pull the oplog from…
GridFS is a MongoDB specification for storing and retrieving files larger than the 16MB document limit. It splits a file into small chunks (default 255KB) stored in two collections: fs.files (metadata) and fs.chunks (binary data). Use when: you must store files (audio, video, large images)…
A transaction lets you run a series of operations (read/write) across multiple documents or collections while guaranteeing atomicity: if one operation fails, everything rolls back, and uncommitted data is not visible to other transactions (isolation). In MongoDB, transactions run through a session: the client opens…
- updateOne: changes only part of a document via operators like $set, $inc, $push. Fields you don't mention stay as they are. - replaceOne: replaces the entire document with a new one (keeping the same id). Any field you omit is lost. An HTTP analogy:…
Run explain('executionStats') and read three numbers first; everything else comes later. - stage: COLLSCAN means a full collection scan — no usable index. IXSCAN means an index is being used. - totalDocsExamined vs nReturned: examining 500,000 documents to return 20 signals a wrong or non-selective…
Because a $match at the front of the pipeline runs like a find() on the collection, so it can use an index (besides it, only $sort and $geoNear at the front of the pipeline can use indexes). Once data has passed through $group, $project, or…
Because an unbounded array causes three problems at once: 1. Hitting the 16MB ceiling. A document maxes out at 16MB. The comments array of a viral post will hit it and every later write fails. 2. Writes get slower. As the document grows, WiredTiger must…
A change stream lets an application subscribe to data changes (insert/update/delete) in real time without polling. It reads from the replica set oplog, so it requires a replica set or sharded cluster — it does not work on a standalone server. Common uses: pushing real-time…
Decide based on access pattern and growth bounds, not on a reflex that "NoSQL means embed". Embed when: the child data is always read with the parent, its count is bounded, and it is rarely updated on its own. Reference when: the child data grows…
ESR = Equality, Sort, Range — order compound index fields as: equality predicates first, then the sort fields, then range predicates ($gt, $lt, ranged $in). Why: an index is an ordered structure. Equality narrows to one contiguous range; inside that range entries are already ordered…
Separate two situations: the index cannot be used (you see COLLSCAN), and the index is used but almost fully scanned (still IXSCAN, but totalKeysExamined is close to the number of index entries). Both are slow. The most common cases: - $regex not anchored at the…
A covered query is one MongoDB answers entirely from an index, without reading documents from the collection. In explain you see an IXSCAN with no FETCH after it, and totalDocsExamined is 0. Conditions: 1. Every field in the filter is in the index. 2. Every…
A sparse index only skips documents missing the indexed field. A partial index indexes only documents matching an arbitrary filter — it is the more general option and the one to reach for by default. The payoff: if 95% of orders are completed, the index…
That is the 100MB per-stage memory limit for aggregation pipelines (it applies to $group, $sort, $bucket, and others). allowDiskUse: true lets the stage spill to disk and exceed the cap. But it is a workaround, not a root-cause fix: spilling is far slower and puts…
Use schema validation at the database layer via $jsonSchema. It is the last line of defence, independent of Mongoose/application validation — which matters because ad-hoc scripts and background jobs often write straight to the database, bypassing the ORM. bsonType: 'number' accepts int, long, double and…