Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 70 ยท Practice and wrap-up

MongoDB Interview Questions

Prepare for MongoDB interviews with concise answers on concepts, indexing, schema design, aggregation, transactions, replication and sharding, plus a quiz.

Interviewers rarely want a recited definition. They want to hear that you know why MongoDB behaves the way it does, what it costs, and when you would choose something else. This lesson collects the questions that come up most often, grouped by topic, with answers short enough to say out loud in under a minute. Each answer links back to the lesson that teaches the topic in depth.

The shell snippets in the answers are real mongosh syntax and read-only, because the site has no MongoDB server. The two TryIts are stand-ins: small pieces of plain JavaScript that reproduce two behaviors interviewers love to probe (null versus missing fields, and why sorting needs a deterministic tie-breaker). They are not MongoDB itself.

What interviewers listen for

Reasoning Why, not just what.
Trade-offs Every choice has a cost.
Experience Mistakes you have seen.
Measuring explain() before opinions.

A short, honest answer beats a long, vague one.

1 / 2

Concepts

What is MongoDB, and how does it differ from a relational database? MongoDB is a document database. Data lives in collections of BSON documents, which can hold nested objects and arrays, and documents in one collection need not share the same fields. A relational database spreads an entity across tables joined at query time and enforces a rigid schema. MongoDB favors storing together what you read together. See What Is MongoDB?.

What is BSON, and why not plain JSON? BSON is a binary encoding of JSON-like documents. It adds types JSON lacks (ObjectId, Date, Int32, Int64, Decimal128, binary data), supports fast traversal, and is what the server stores and transmits. See BSON Types.

What is _id? Every document has a unique _id, indexed automatically and immutable. If you do not supply one, the driver generates an ObjectId, which embeds a creation timestamp, a random value and a counter. See _id and ObjectId.

Is MongoDB schemaless? Not really: it has a flexible schema. The application still depends on a shape, so you should model it deliberately and can enforce it with $jsonSchema validation. See Schema Validation.

What is the maximum document size? 16 MB. It is a guard against unbounded growth, which is the real design problem; documents should stay far smaller.

When would you not choose MongoDB? When the data is highly relational with many ad hoc joins across entities, when you need strong multi-table integrity constraints enforced by the database, or when the team's workload is mostly complex reporting that a relational engine handles natively.

CRUD and queries

What is the difference between updateOne with $set and replaceOne? $set changes only the named fields. replaceOne swaps the entire document (keeping _id) with the one you provide, so omitted fields disappear. See Updating Documents and Upserts, Replace and findAndModify.

What does an upsert do? With upsert: true, if no document matches, MongoDB inserts a new one built from the filter's equality fields plus the update. $setOnInsert applies fields only in that insert case.

How do you match a document by one array element satisfying several conditions? Use $elemMatch. Without it, separate conditions may be satisfied by different elements of the same array. See Array Query Operators.

What is the difference between { field: null } and { field: { $exists: false } }? { field: null } matches documents where the field is null or missing. $exists: false matches only missing fields. See Element and Evaluation Operators.

JS null versus missing, in a stand-in matcher

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Why is skip a poor way to paginate deep? The server still walks past every skipped entry, so cost grows with the offset. Range-based pagination (filter on the last seen sort key, then limit) stays fast. See Sorting, Limiting and Skipping.

Why add _id to a sort? Sort ties have no guaranteed order, so pages can repeat or skip documents. A unique tie-breaker makes the order deterministic.

JS Sorting with and without a tie-breaker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Indexing

What is an index and what does it cost? A B-tree structure over one or more fields that lets the server find documents without scanning the collection. The costs are disk and memory space and slower writes, because every insert, update of an indexed field and delete must maintain each index. See How Indexes Work.

What is a compound index and does field order matter? An index on several fields. Order matters: it supports queries on a prefix of its fields and determines sort support. See Designing Compound Indexes.

What is the ESR rule? A guideline for ordering compound-index fields: Equality fields first, then Sort fields, then Range fields.

What is a covered query? One answered entirely from an index: every filtered and returned field is in the index and _id is excluded from the projection. The plan shows no document fetch.

What index types exist beyond single-field and compound? Multikey (arrays), text, hashed, geospatial (2dsphere), wildcard, partial, sparse, unique and TTL. See Index Types.

How do you check whether a query uses an index?

JavaScript
db.orders.find({ status: "paid", total: { $gt: 100 } }).explain("executionStats")

Look at the winning plan stage (IXSCAN is good, COLLSCAN is a full scan) and compare totalDocsExamined with nReturned. A large gap means the index is not selective for that query. See explain() and the Profiler.

Why can too many indexes hurt? Each one slows writes and consumes RAM that the working set also needs. Drop indexes that no query uses.

Schema design

Embed or reference? Embed when data is read together, the child set is bounded, and you want atomic updates on one document. Reference when the related data is large, unbounded, shared by many parents or changes independently. See Embedding vs Referencing.

What is the unbounded array problem? An array that grows without limit (every comment ever, every event) bloats the document, slows updates and eventually hits the 16 MB limit. Move the items to their own collection or use the bucket pattern.

Name a few schema design patterns. Subset (keep only the hot items embedded), bucket (group many small records into time windows), computed (store precomputed values), extended reference (copy a few fields from the referenced document), and schema versioning (a version field so old and new shapes coexist). See Schema Design Patterns.

How do you model many-to-many relationships? Usually arrays of references on one or both sides, or a separate linking collection when the relationship has its own attributes. See Modeling Relationships.

Aggregation

What is the aggregation pipeline? An ordered list of stages, each transforming the stream of documents passed to the next. See The Aggregation Pipeline.

Why put $match early? It shrinks the stream before expensive stages and, as a leading stage, can use an index. The optimizer reorders some stages, but do not rely on it.

How do $group and $project differ? $group collapses many documents into one per key and computes accumulators such as $sum and $avg. $project reshapes each document one-to-one. See Grouping with $group.

How do you do a join? $lookup joins to another collection in the same database. It works, but it costs more than reading one embedded document, which is a reason to embed data that is always read together. See Joining with $lookup.

What happens when a stage exceeds its memory limit? Blocking stages such as $group and $sort have a per-stage memory limit; with allowDiskUse they can spill to disk. See Aggregation Performance and Explain.

Transactions and consistency

Is MongoDB ACID? Single-document operations are atomic, including updates to nested fields and arrays. Since version 4.0, multi-document transactions provide ACID semantics on replica sets, and since 4.2 on sharded clusters. They cost more than single-document writes, so good embedding avoids needing them. See Atomicity and Single-Document Writes and Multi-Document Transactions.

What are write concern and read concern? Write concern says how many members must acknowledge a write (w: 1, w: "majority") and whether it must be journaled. Read concern chooses what level of data a read may see (local, majority, and others). See Read and Write Concerns.

How do you avoid lost updates without a transaction? Use atomic update operators ($inc, $push) instead of read-modify-write, or an optimistic-concurrency version field checked in the update filter.

JavaScript
db.products.updateOne(
  { _id: 7, version: 3 },
  { $set: { price: 12 }, $inc: { version: 1 } }
)
// matchedCount 0 means someone else changed it first: re-read and retry

Replication and sharding

What is a replica set? A group of mongod processes holding the same data: one primary takes writes, secondaries replicate from its oplog, and an election picks a new primary if it fails. See Replica Sets.

What is sharding and when do you need it? Horizontal partitioning of a collection across shards by a shard key, fronted by mongos routers with metadata on config servers. You need it when data or write throughput outgrows one replica set, not before. See Sharding.

What makes a good shard key? High cardinality, even distribution of values and writes, and inclusion in the common queries so they target one shard. A monotonically increasing key such as a timestamp sends all new writes to one shard. A hashed key spreads writes but makes range queries hit many shards.

Replication or sharding for high availability? Replication. Sharding is for scale; each shard is itself a replica set.

Security and operations

How do you secure a deployment? Enable authentication, grant least-privilege roles, bind to private interfaces, require TLS, encrypt at rest, audit access, and test your backups. See Securing a Deployment.

What is operator injection? Untrusted JSON inserted directly into a filter, so an attacker sends { "$ne": null } where a password string was expected. Validate types and never pass raw request bodies as filters. See NoSQL Injection and Safe Queries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which filter matches documents where phone is null OR the field is missing?

    Equality with null matches both explicit nulls and missing fields. $exists false matches only missing fields, and $type null matches only explicit nulls.
  2. 2. A compound index should list fields in which order according to the ESR rule?

    Equality fields narrow the scan most precisely, sort fields then deliver ordered results without a blocking sort, and range fields come last.
  3. 3. Why is a monotonically increasing shard key (such as a timestamp) usually a bad choice?

    New values always sort after existing ones, so inserts target the shard holding the highest range and the other shards sit idle.
  4. 4. What is the best way to avoid a lost update when two clients modify the same document?

    Atomic operators apply the change on the server in one step, and a version check makes a conflicting write match zero documents so you can retry.

Summary

  • Answer with reasoning and trade-offs, not definitions alone: embed or reference, index or not, transaction or atomic operator.
  • Know the classic gotchas: null versus missing, $elemMatch, deep skip, sort ties, unbounded arrays.
  • Indexes speed reads and slow writes; design them with ESR and verify with explain("executionStats").
  • Single-document writes are atomic; multi-document transactions exist but cost more.
  • Replication gives availability, sharding gives scale, and the shard key decides whether sharding works well.

Keep the commands at your fingertips with the MongoDB Cheat Sheet.