MongoDB Interview Questions and Answers

Documents, indexes, the aggregation pipeline and data modelling.

Practise 10 random 10 peer-reviewed questions
MongoDB Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level MongoDB interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 How does MongoDB differ from a relational database? Easy

MongoDB is a document database. Data is stored as flexible BSON documents inside collections instead of rows in tables with a fixed schema. Each document can have its own fields, and nested objects and arrays are native.

db.users.insertOne({
  name: "Ada",
  roles: ["admin", "author"],
  address: { city: "London" }
});

Key differences:

  • Relationships are modelled by embedding or by references, and joins are optional via $lookup.
  • Schema is enforced by the application, optionally validated with JSON Schema validators.
  • Scaling out uses replica sets for availability and sharding for horizontal scale.
  • Transactions exist but are not the primary consistency unit; single-document writes are atomic.

Use MongoDB when the access pattern is document-oriented and the schema evolves quickly. Prefer a relational database when you need complex multi-table joins and strong relational integrity.

2 How do indexes work in MongoDB and what is a compound index? Easy

An index is a B-tree structure storing a sorted subset of a collection's fields, letting the planner find documents without scanning everything. Without an index a query does a COLLSCAN; with one it can do an IXSCAN.

A compound index covers multiple fields in a defined order:

db.orders.createIndex({ customerId: 1, createdAt: -1 });

Order matters. This index supports queries on customerId alone and on customerId plus createdAt, but not on createdAt alone, because of the leftmost-prefix rule. Direction matters for sorts: sorting customerId ascending and createdAt descending uses this index directly.

Every index speeds reads but slows writes and consumes memory, so create only what your queries need. Use explain("executionStats") to confirm an index is used and to see how many documents were examined versus returned.

3 When would you embed versus reference documents in MongoDB? Medium

Embed when the child data is always read with the parent, is bounded in size, and belongs to that parent. Reference when the child is large, unbounded, or shared across many parents by storing a field such as user_id in another collection.

Rules of thumb:

  • One-to-few: embed the subdocuments.
  • One-to-many: store an array of references.
  • One-to-squillions: keep parent_id on the child so the parent array cannot grow without limit.
  • Many-to-many: references on both sides, or a join collection.

Embedding avoids extra round trips and keeps reads fast, but updating shared embedded data in many places is error-prone and documents have a 16 MB limit. Referencing keeps data normalized and easier to update independently, at the cost of $lookup or extra queries. A common hybrid stores a small summary embedded and the full record separately.

4 Write an aggregation pipeline that returns the top three products by revenue. Medium

Pipelines pass documents through stages, transforming them step by step.

db.orders.aggregate([
  { $match: { status: "paid" } },
  { $unwind: "$items" },
  { $group: {
      _id: "$items.productId",
      revenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } }
  }},
  { $sort: { revenue: -1 } },
  { $limit: 3 },
  { $lookup: {
      from: "products",
      localField: "_id",
      foreignField: "_id",
      as: "product"
  }},
  { $project: { _id: 0, name: { $first: "$product.name" }, revenue: 1 } }
]);

$match first so later stages process fewer documents. $unwind flattens the items array. $group aggregates by product, $sort and $limit select the top three, and $lookup enriches with product names. Put the most selective stages early and project away fields you no longer need.

5 What is the $lookup stage and what are its trade-offs? Medium

$lookup performs a left outer join against another collection in the same database. The basic form matches localField against foreignField and returns matches in an "as" array. The pipeline form lets you run a sub-pipeline with variables, which is more flexible but slower.

db.orders.aggregate([
  { $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customer"
  }},
  { $unwind: "$customer" }
]);

Trade-offs: $lookup is convenient but does not use indexes as efficiently as a native join and gets expensive at scale, especially when the foreign collection is large. It runs per input document, so combine it with an early $match and an index on the foreign field. For high-volume or frequently joined data, consider embedding a denormalized copy instead.

6 What are replica sets and how do they provide high availability? Medium

A replica set is a group of nodes holding the same data: one primary and two or more secondaries. All writes go to the primary. Secondaries replicate the oplog and can serve reads when the client uses a secondary read preference.

If the primary fails, the remaining members hold an election and promote a secondary. A majority of voting members must be available to elect a primary, so an odd number of members, typically three, is recommended, or an arbiter can break ties. Elections usually complete in seconds.

Replication is asynchronous by default, so a secondary can lag. Read concern majority with write concern majority gives reads that reflect acknowledged writes. Linearizable read concern is stronger but slower. Monitor replication lag and rehearse failover, and remember that a network partition can leave the old primary isolated until it steps down.

7 Explain write concern and read concern in MongoDB. Medium

Write concern controls how many nodes must acknowledge a write before it counts as successful. w:1 means the primary acknowledged it; w:"majority" means a majority of replica set members did. Adding j:true ensures it is journaled to disk. Higher write concern is safer but slower.

Read concern controls the consistency guarantee of a read:

  • local returns the node's latest data and can expose writes later rolled back.
  • majority returns data acknowledged by a majority.
  • linearizable guarantees the read reflects all prior majority-acknowledged writes.
  • snapshot reads a consistent point in time, often used with transactions.

Combine them for the guarantee you need. For example, w:"majority" with readConcern:"majority" prevents reading data that might be rolled back. Financial writes often use majority, while high-throughput logging may accept w:1.

8 How do you model a one-to-many relationship in MongoDB? Medium

The answer depends on the size of the "many" side and the access pattern.

One-to-few: embed an array of subdocuments. A user with a handful of addresses embeds them, so one read returns everything.

One-to-many: store an array of references on the parent, or store the parent id on each child. A post with a few hundred comments can embed them, but millions of comments should be stored with post_id on each comment and an index on that field.

One-to-squillions: never embed an unbounded array. Keep parent_id on the child and query by it, because documents are capped at 16 MB and huge arrays hurt update performance.

Many-to-many: reference on both sides, or use a join collection. Always model around the queries you actually run, not around normalization purity.

9 How does sharding work in MongoDB? Hard

Sharding horizontally partitions a collection across mongos routers and shards. You choose a shard key, and MongoDB splits the key space into chunks distributed and balanced across shards.

Two strategies:

  • Ranged sharding: contiguous key ranges per shard, good for range queries but can create hotspots on monotonic keys.
  • Hashed sharding: hashes the key for even distribution, good for write scaling but poor for range queries.

The shard key must be present in every document and is immutable in older versions. A poor key causes jumbo chunks or an unbalanced cluster; a monotonically increasing timestamp sends all writes to one shard. Include a high-cardinality, frequently queried field, or use a compound key combining a coarse partition with a fine field. Queries including the shard key are targeted; others become scatter-gather and hit every shard.

10 When should you prefer the aggregation framework over find? Hard

Use find for simple filtering, projection, sorting and pagination on a single collection. It is lightweight and uses indexes efficiently.

Use aggregate when you must transform data: group, join, reshape, compute derived values, or run multi-stage logic. Aggregation can still use indexes for $match and $sort when they appear early.

db.sales.aggregate([
  { $match: { region: "EMEA", date: { $gte: ISODate("2024-01-01") } } },
  { $group: { _id: "$productId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } } ]);

Performance pitfalls: stages after $group or $unwind cannot use the original index, $lookup is costly, and a large $sort without an index may spill to disk. Put $match and $sort first, project early to shrink documents, and inspect explain output before shipping.

Frequently Asked Questions About MongoDB Interviews

What do hiring managers evaluate in MongoDB technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing MongoDB questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.