Interview questions · Tech stack

MongoDB Interview Questions & Answers (2026)

These interviews test your grasp of MongoDB data modeling, query optimization, replication, and sharding. Demonstrate clear concepts, explain trade‑offs, and show practical experience with indexes and aggregation pipelines to convince interviewers you can design and maintain reliable, high‑performance NoSQL solutions.

23 questions · updated Aug 29, 2026

Quick facts

Typical roundsPhone screen, technical coding, system design, and on‑site deep dive
Core topicsData modeling, CRUD ops, indexes, replication, sharding, aggregation
Preferred experience2‑5 years building production MongoDB services
Common toolsMongoDB Compass, mongosh, Atlas, Mongoose

Questions

Beginner

What is the difference between a primary key and an index in MongoDB?

The primary key is the _id field, automatically indexed and unique for each document. Regular indexes are optional structures that improve query performance on other fields. Interviewers expect you to note that _id guarantees uniqueness and fast lookups, while secondary indexes can be compound, sparse, or TTL, and must be managed to avoid excessive write overhead.

GoogleAmazon

How does MongoDB achieve high availability?

MongoDB uses replica sets, a group of mongod instances where one node is primary and others are secondaries. Writes go to the primary and are replicated to secondaries via oplog. If the primary fails, an election selects a new primary, ensuring continuous availability. Interviewers look for awareness of write concerns, read preferences, and the impact of network partitions on consistency.

Microsoft

When would you choose embedding over referencing in a schema?

Embed when related data is accessed together and the document size stays under 16 MB, providing atomic updates and fewer round‑trips. Reference when the relationship is many‑to‑many, data changes independently, or the embedded array could grow unbounded. A strong answer mentions read/write patterns, document growth, and the trade‑off between denormalization and consistency.

Netflix

What is a TTL index and when would you use it?

A TTL (time‑to‑live) index automatically removes documents after a specified number of seconds or at a date field. It is ideal for session data, caches, or logs where data becomes irrelevant after a set period. Interviewers look for awareness of background thread cleanup, the 60‑second granularity, and the impact on write performance.

Snapchat

What are the limits of a MongoDB document and why do they exist?

A document cannot exceed 16 MB, a limit set to keep memory usage predictable and to avoid excessive network payloads. This encourages proper data modeling, such as splitting large blobs into GridFS or referencing related data. Interviewers look for awareness of this limit and strategies to handle large binary data.

Zoom

How does MongoDB handle schema validation and why would you enable it?

Schema validation uses JSON Schema rules defined in collMod or createCollection to enforce field types, required fields, and value ranges. Enabling it prevents malformed data, aids data quality, and can catch bugs early. Interviewers look for examples like enforcing email format or numeric ranges, and note the performance impact is minimal.

GitLab

Intermediate

Explain the purpose of the oplog in MongoDB replication.

The oplog (operations log) records all write operations on the primary in a capped collection. Secondaries tail this log to apply the same changes in order, keeping data synchronized. Interviewers expect you to discuss its size constraints, the impact on replication lag, and how write concern w:majority depends on oplog durability.

Adobe

What are the trade‑offs of using a capped collection?

Capped collections provide high‑throughput inserts and automatic FIFO deletion, ideal for logs or time‑series data. However, they cannot grow beyond a fixed size, lack document deletion, and do not support indexes beyond the natural order. Interviewers look for understanding of use cases versus the inability to update existing documents without overwriting subsequent entries.

Twitter

How does the aggregation framework differ from map‑reduce?

Aggregation pipelines process data in stages, are optimized by the query engine, and run within the mongod process, offering better performance and lower latency. Map‑reduce executes JavaScript functions, can span multiple shards, but is slower and less flexible. Interviewers want you to cite pipeline operators, memory limits, and when map‑reduce is still useful for complex transformations.

Shopify

Describe how sharding works and when you would enable it.

Sharding partitions a collection across multiple shards using a shard key. Each chunk contains a range of shard key values and is moved as data grows. Enable sharding when a dataset exceeds a single node's storage or I/O capacity, or when you need horizontal read/write scaling. Interviewers expect discussion of shard key selection, balancing, and the impact on query routing.

Uber

What is a write concern and why is it important?

Write concern specifies the level of acknowledgment required from replica set members before a write is considered successful. For example, w:1 acknowledges the primary only, while w:majority ensures a majority of nodes have persisted the write. It balances durability against latency; interviewers look for examples like w:majority for financial data versus w:0 for high‑throughput logging.

PayPal

How do you ensure data consistency when reading from secondaries?

Use read preference 'primaryPreferred' or 'secondary' with a suitable readConcern (e.g., majority) to guarantee that reads reflect committed data. Explain the trade‑off: lower latency versus potential stale data. Interviewers expect you to mention the impact of network lag and how to handle eventual consistency in application logic.

Dropbox

What is the purpose of the $lookup stage in aggregation?

$lookup performs a left‑outer join between two collections, allowing you to combine related data without denormalizing. It can be optimized with indexes on the foreign field and may be executed on the primary or secondary depending on the pipeline. Interviewers want you to discuss pipeline ordering, memory limits, and when $lookup can replace manual client‑side joins.

Pinterest

How does MongoDB's journaling affect durability and performance?

Journaling writes operations to a pre‑allocated journal file before applying them to data files, ensuring durability after a crash. It adds a small latency (typically 1‑2 ms) but protects against corruption. Interviewers expect you to discuss the journalCommitInterval, its impact on writeConcern w:majority, and how disabling journaling can improve throughput at the cost of data safety.

Slack

Explain the difference between $match and $filter in aggregation pipelines.

$match filters documents at the pipeline level, reducing the number of documents passed to subsequent stages. $filter operates on array fields within a single document, returning a subset of array elements. Interviewers expect you to illustrate when each is appropriate, such as early $match for performance versus $filter for array manipulation.

Reddit

Advanced

How would you troubleshoot a slow query in MongoDB?

First, run explain() to view the query plan and identify collection scans or unindexed predicates. Then, check index usage, cardinality, and whether the query can be covered. Review server metrics for CPU, memory, and lock statistics, and consider adding or refining indexes, rewriting the query, or adjusting schema. Interviewers expect a systematic approach and mention of profiling tools.

LinkedIn

Explain the impact of the WiredTiger cache size on performance.

WiredTiger uses an internal cache (default 50 % of RAM) to hold frequently accessed data and indexes. A cache that is too small causes frequent disk reads and evictions, degrading latency. Conversely, an oversized cache can starve the OS and other processes. Interviewers look for understanding of cache pressure, the use of cacheSizeGB, and monitoring via serverStatus.

Airbnb

What are the consequences of using a non‑unique shard key?

A non‑unique shard key can lead to uneven chunk distribution, causing hotspots where a single shard handles a disproportionate share of reads/writes. It also complicates migrations because multiple documents share the same key range. Interviewers want you to explain why high cardinality and monotonic keys are preferred to achieve balanced load and efficient chunk splits.

Spotify

How does MongoDB handle transactions across multiple documents?

Since version 4.0, MongoDB supports multi‑document ACID transactions using the startTransaction, commitTransaction, and abortTransaction commands. Transactions acquire locks at the shard level, ensuring atomicity across collections and shards. Interviewers expect you to discuss retryable writes, the performance overhead, and when to prefer embedded documents instead of transactions for simplicity.

Square

Describe how MongoDB's readConcern 'linearizable' works.

Linearizable readConcern guarantees that a read reflects the most recent acknowledged write on the primary, providing the strongest consistency. It incurs higher latency because the primary must confirm the write before serving the read. Interviewers expect you to compare it with 'majority' and 'available', and to note its limited support in sharded clusters.

Stripe

When should you use a hashed shard key versus a ranged shard key?

Hashed shard keys distribute documents evenly across shards, preventing hotspots for high‑cardinality fields without natural range queries. Use them when you need uniform write distribution and do not require range queries. Ranged keys preserve order, enabling efficient range scans, but can cause imbalance if the key is monotonic. Interviewers look for scenarios like userId (hashed) versus timestamp (ranged).

GitHub

How would you design a schema for a social media feed that scales to billions of users?

Use a combination of embedding for recent posts (e.g., last 100) and referencing for older content. Partition feeds by userId with a hashed shard key to distribute load evenly. Employ TTL indexes to prune stale entries, and use capped collections for real‑time activity streams. Interviewers look for justification of denormalization, sharding strategy, and read/write trade‑offs.

Meta

What is the role of the $facet stage and when is it useful?

$facet allows multiple pipelines to run in parallel on the same input, producing separate result sets. It is useful for dashboards where you need aggregated metrics (e.g., counts, averages) alongside detailed documents in a single query. Interviewers expect you to discuss memory considerations and how $facet can replace multiple round‑trips.

Salesforce

Common mistakes

  • Choosing a shard key without considering cardinality, leading to hotspots
  • Over‑indexing causing write performance degradation
  • Embedding large, unbounded arrays that exceed document size limits
  • Neglecting read/write concerns, resulting in stale reads or data loss
  • Using $lookup without proper indexes, causing pipeline slowdowns

Study plan

  1. Review core concepts: documents, collections, replica sets, sharding
  2. Practice CRUD operations and index creation with mongosh
  3. Master aggregation pipelines, focusing on $match, $lookup, $facet
  4. Simulate performance issues; use explain() and profiling tools
  5. Implement transactions and configure read/write concerns in a sample app

FAQ

What is the maximum size of a MongoDB document?

A single document cannot exceed 16 MB. This limit keeps memory usage predictable and encourages proper data modeling, such as using GridFS for large files.

Do I need to create indexes for every query?

No. Indexes improve read performance but add write overhead. Create indexes for frequent, selective queries and monitor their impact with explain().

Can MongoDB guarantee strong consistency?

Yes, using readConcern 'linearizable' on the primary provides the strongest consistency, but it incurs higher latency. Most applications balance consistency with performance using 'majority' reads.

How does sharding affect transaction support?

Multi‑document transactions are supported across shards, but they require the involved shards to be part of the same replica set and can be slower due to cross‑shard coordination.

When should I use a TTL index?

Use TTL indexes for data that expires after a fixed period, such as session tokens or logs. They automatically delete stale documents, reducing storage and simplifying cleanup.

Related

Ready for your next interview?

Download MiPrep AI. Load your resume and the job description. Show up ready.

Free tier · No credit card · macOS 14+ · Windows 10+

Free tier · No credit card · Runs on your Mac or Windows machine