00:00

MongoDB Interview Questions and Answers

Last updated: 12 min read

These questions cover what interviewers most often ask about MongoDB, from fundamentals to production topics. Each answer is short enough to say out loud in an interview, with an example where it helps. They are grouped by topic and get harder towards the end.

Interviewers value reasons more than definitions. For each answer, be ready to explain when you would use the feature and what trade-off it brings.

1. MongoDB Basics

Q1. What is MongoDB?

MongoDB is a general-purpose, document-oriented NoSQL database. It stores data as BSON documents grouped into collections, supports a flexible schema, rich queries and aggregation, secondary indexes, replication for high availability, sharding for horizontal scaling, and multi-document ACID transactions.

Q2. What is the difference between a document, a collection and a database?

A document is a single record made of field-value pairs, similar to a row. A collection groups documents, similar to a table, but without a fixed structure. A database is a container for collections, with its own permissions and files.

Q3. What is BSON and why does MongoDB use it instead of JSON?

BSON (Binary JSON) is a binary encoding of JSON-like documents. It is faster to scan because field lengths are stored up front, and it supports extra types that JSON lacks: dates, 32/64-bit integers, Decimal128, ObjectId and binary data.

Q4. What is an ObjectId?

The default type of _id: a 12-byte value made of a 4-byte timestamp, a 5-byte random value per process and a 3-byte counter. It is generated by the client without contacting the server, is unique in practice and sorts roughly by creation time. ObjectId().getTimestamp() returns its creation time.

Q5. Is MongoDB schemaless?

Not really: it has a flexible schema. Documents in a collection can differ, but applications still rely on a structure, and you can enforce rules with $jsonSchema validation on a collection. "Schema on read" plus optional validation is the more accurate description.

Q6. What is the maximum document size, and how do you store larger files?

16 MB. Larger files go in object storage (such as Amazon S3) with a reference in the document, or in MongoDB using GridFS, which splits a file into chunks across the fs.files and fs.chunks collections.

Q7. How do you create a database and a collection?

Implicitly. use shop switches to the database, and the first insert creates both the database and the collection. db.createCollection() is only needed when you want options such as validation, time series or a capped size.

2. Data Modeling

Q8. When do you embed and when do you reference?

Embed data that is read together, belongs to one parent and stays bounded in size, such as order items in an order. Reference data that is large, shared by many documents, changes independently or grows without limit, such as customers referenced by orders or a product's millions of reviews.

Q9. What is the "unbounded array" problem?

An array that keeps growing, such as every comment ever posted inside a post document, eventually approaches the 16 MB limit, makes each update more expensive and bloats every read. Solutions are referencing (a separate comments collection), the subset pattern (embed only the latest N items) or the bucket pattern (group items into fixed-size documents).

Q10. Name some MongoDB schema design patterns.

  • Attribute pattern: store varying attributes as an array of key-value pairs that can be indexed together.
  • Bucket pattern: group many small items (for example readings per hour) into one document.
  • Computed pattern: pre-calculate values such as totals on write instead of on every read.
  • Extended reference: copy a few frequently needed fields from a referenced document to avoid joins.
  • Outlier pattern: handle rare, very large cases differently from the common case.
  • Schema versioning: add a schemaVersion field so old and new document shapes can coexist.

Q11. How do you implement a one-to-many relationship?

For "one-to-few", embed an array of child documents. For "one-to-many", store an array of child ids in the parent or, more commonly, the parent id in each child. For "one-to-squillions", always store the parent id in each child and index it.

3. Queries and Aggregation

Q12. What is the difference between find() and aggregate()?

find() filters, projects, sorts and pages documents. aggregate() runs a pipeline of stages that can also group, compute new fields, unwind arrays, join collections with $lookup, and write results with $out or $merge.

Q13. Why does $elemMatch exist?

Without it, conditions on an array of documents can be satisfied by different elements. { items: { $elemMatch: { sku: "A1", qty: { $gte: 2 } } } } requires both conditions on the same element.

Q14. Explain a typical aggregation pipeline.

mongosh
db.orders.aggregate([
  { $match: { status: "SHIPPED", createdAt: { $gte: ISODate("2026-01-01") } } },
  { $group: { _id: "$customerId", revenue: { $sum: "$total" } } },
  { $sort: { revenue: -1 } },
  { $limit: 10 }
])

It filters early with $match (which can use an index), groups by customer, sorts by revenue and keeps the top ten. Placing $match and $project early reduces the data flowing through later stages.

Q15. How does $lookup work, and should you use it often?

$lookup performs a left outer join with another collection in the same database, adding matching documents as an array. It is useful for reports and occasional joins, but if every request needs a $lookup, the schema may need embedding or an extended reference instead. Index the foreign field.

Q16. What is the difference between updateOne(), replaceOne() and findOneAndUpdate()?

updateOne() changes specific fields with operators. replaceOne() replaces the whole document except _id. findOneAndUpdate() updates atomically and returns the document, before or after the change, which is useful for counters and job queues.

Q17. What is an upsert?

An update with upsert: true that inserts a new document when nothing matches. Use $setOnInsert for fields that should be set only on insert, and a unique index on the filter fields to stop concurrent upserts from creating duplicates.

4. Indexing and Performance

Q18. What index types does MongoDB support?

Single field, compound, multikey (arrays), text, 2dsphere/2d (geospatial), hashed, wildcard and clustered indexes, with options for unique, partial, TTL, sparse, hidden and collation.

Q19. What is the ESR rule?

A guideline for ordering fields in a compound index: Equality fields first, then Sort fields, then Range fields. It lets the index narrow results exactly, return them already sorted, and then scan the range.

Q20. How do you find out why a query is slow?

Run it with explain("executionStats"). Look for COLLSCAN, an in-memory SORT stage, and a large gap between totalDocsExamined and nReturned. Also use the database profiler (db.setProfilingLevel(1, { slowms: 100 })), slow query logs and, on Atlas, the Performance Advisor.

Q21. What is a covered query?

A query whose filter and returned fields are all in one index, with _id excluded unless it is in the index. MongoDB answers it from the index alone without reading documents, so totalDocsExamined is 0.

Q22. What is a TTL index?

An index on a date field with expireAfterSeconds. A background task deletes documents older than that age, roughly once a minute. It is used for sessions, tokens, temporary data and logs.

Q23. Why not index every field?

Every index uses disk and RAM and must be updated on every write, so too many indexes slow down inserts and updates and push useful data out of memory. Create indexes for real query patterns, remove unused ones (check $indexStats), and drop redundant prefixes.

5. Replication and Sharding

Q24. What is a replica set?

A group of mongod instances holding the same data: one primary for writes and secondaries that replicate its oplog. If the primary fails, the voting members elect a new one automatically, typically within seconds.

Q25. Why should a replica set have an odd number of voting members?

Elections need a strict majority. Three members tolerate one failure and four members also tolerate only one, so the fourth adds cost without availability. At most 7 of a set's up to 50 members can vote.

Q26. What are write concern and read concern?

Write concern sets how many members must acknowledge a write; w: "majority" (the default since 5.0) guarantees the write survives failover. Read concern sets which data a read may return; majority returns only data acknowledged by a majority, which cannot be rolled back.

Q27. What is read preference?

It decides which members serve reads: primary (default), primaryPreferred, secondary, secondaryPreferred or nearest. Secondary reads offload work but may be slightly stale because of replication lag.

Q28. What is sharding, and how do you choose a shard key?

Sharding splits a collection across multiple replica sets (shards); mongos routers send each query to the right shards using metadata on the config servers. A good shard key has high cardinality, distributes writes evenly (avoid monotonically increasing values such as timestamps unless hashed), and appears in most queries so they can target a single shard. MongoDB 5.0+ can change a shard key with reshardCollection.

Q29. What is the difference between replication and sharding?

Replication copies all data to several servers for availability; sharding splits data across servers for scale. Production sharded clusters use both, because every shard is a replica set.

6. Transactions and Consistency

Q30. Are MongoDB operations atomic?

Every write to a single document is atomic, including changes to nested fields and arrays. For changes that span documents or collections, MongoDB provides multi-document ACID transactions: on replica sets since 4.0 and on sharded clusters since 4.2.

Q31. When should you use a multi-document transaction?

When several documents must change together or not at all, such as moving money between accounts or reserving stock while creating an order. Keep transactions short: by default they are aborted after 60 seconds, and long transactions increase contention. Often a better schema (embedding) removes the need for one.

Java (sync driver)
try (ClientSession session = client.startSession()) {
    session.withTransaction(() -> {
        accounts.updateOne(session, eq("_id", "A"), inc("balance", -500));
        accounts.updateOne(session, eq("_id", "B"), inc("balance",  500));
        return null;
    });
}

Q32. What are change streams?

A way to subscribe to real-time inserts, updates, deletes and other changes on a collection, database or whole deployment, built on the oplog. They are resumable with a resume token and are used for event-driven microservices, cache invalidation and syncing to search or analytics systems.

7. Security and Operations

Q33. How do you secure a MongoDB deployment?

  • Enable authentication (SCRAM, x.509, or LDAP/OIDC in Enterprise and Atlas) and use role-based access control with least privilege.
  • Bind to private network interfaces only and restrict access with firewalls or IP access lists.
  • Encrypt traffic with TLS and data at rest; use Client-Side Field Level Encryption or Queryable Encryption for sensitive fields.
  • Enable auditing, keep versions patched, and secure backups.

Q34. How do you back up MongoDB?

mongodump/mongorestore for small and medium databases (with --oplog on replica sets), filesystem snapshots for large self-managed deployments, and Atlas Cloud Backup or Ops Manager for continuous backups with point-in-time restore. Backups must be tested by restoring them regularly.

Q35. What is a time series collection?

A collection type, created with the timeseries option, for measurements over time. MongoDB stores readings from the same source in compressed buckets, which reduces storage and speeds up time-range queries, and it supports automatic expiry with expireAfterSeconds.

Q36. What is the WiredTiger storage engine?

MongoDB's default storage engine since 3.2. It provides document-level concurrency control, compression of data and indexes (snappy by default, with zlib and zstd options), a write-ahead journal for crash recovery, and an internal cache that by default uses 50% of (RAM minus 1 GB), or 256 MB, whichever is larger.

Q37. What is new in MongoDB 8.0?

Broad performance improvements for reads, writes and bulk operations; easier horizontal scaling (moving unsharded collections between shards, faster resharding, config shards); range queries on Queryable Encryption fields; query settings that let administrators shape query behaviour without code changes; and a bulkWrite command that spans multiple collections.

8. Scenario Questions

Q38. Your application's product listing page has become slow. What do you check?

  1. Find the slow queries in the profiler or slow query log.
  2. Run explain("executionStats") to look for collection scans and in-memory sorts.
  3. Create or adjust a compound index following the ESR rule; use projection to return fewer fields.
  4. Replace deep skip() pagination with range-based pagination.
  5. Check whether the working set still fits in RAM, and look at server metrics such as CPU, disk and cache eviction.

Q39. Someone ran deleteMany({}) on a production collection. How do you recover?

Replication will not help, because the delete was replicated. Restore the collection from the latest backup into a separate namespace (for example with mongorestore --nsFrom/--nsTo), then copy back the data. With point-in-time backups (Atlas or Ops Manager) or a delayed secondary, restore to the moment just before the delete. Afterwards, tighten permissions and add safeguards.

Q40. How would you design a collection for user activity events that will grow to billions of documents?

Use a time series collection (or the bucket pattern) with the user or device as the meta field, an expiry for old data, and indexes that match the dashboards' queries. If a single replica set cannot handle the write volume, shard on a key that spreads writes evenly, such as a hashed user id, and archive cold data to cheaper storage.

9. Final Tips

  • Learn the "why" behind each feature: embedding vs referencing, ESR, write concern, shard key choice.
  • Practise in mongosh: write queries, aggregations and explain() plans yourself.
  • Be ready to compare MongoDB with relational databases honestly, including when you would not choose MongoDB.
  • Revise the related tutorials: Indexing, Replication and Backup and Restore.