Technology

MongoDB Interview Questions and Answers

MongoDB is the most popular NoSQL document database. These MongoDB interview questions cover documents, collections and CRUD for freshers, then schema design, indexing, the aggregation pipeline, transactions, replica sets and sharding for experienced developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise MongoDB questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
MongoDB Interview Questions with answers. Examples: What is MongoDB, and how is it different from a relational database? What is the _id field? What are the basic CRUD operations in MongoDB? When do you embed documents and when do you reference them?
MongoDB Interview Questions: 30 questions with model answers on this page.

Basic MongoDB interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is MongoDB, and how is it different from a relational database?

Answer flow · 4 steps
  1. MongoDB is a NoSQL database that stores data as flexible JSON-like documents (BSON) in collections, instead of rows in tables with a fixed schema.

  2. Related data is often embedded in one document, reducing joins.

  3. It scales horizontally with sharding.

  4. Relational databases are better for highly relational data needing complex joins and strict constraints.

2. What is the _id field?

Every document has a unique _id field that acts as the primary key. If you do not provide one, MongoDB generates an ObjectId, a 12-byte value containing a timestamp, a random value and a counter, so IDs are roughly ordered by creation time.

3. What are the basic CRUD operations in MongoDB?

insertOne and insertMany create documents; find and findOne read them with filters such as { age: { $gt: 25 } } and projections; updateOne, updateMany and replaceOne change documents using operators such as $set, $inc and $push; deleteOne and deleteMany remove them.

4. What is BSON?

Answer flow · 3 steps
  1. BSON (Binary JSON) is the binary format MongoDB uses to store documents.

  2. It is faster to scan than text JSON and supports extra types such as ObjectId, Date, Decimal128 for exact money values, 32- and 64-bit integers, binary data and regular expressions.

  3. Drivers convert between BSON and your language's objects automatically.

5. Which query operators do you use in MongoDB?

Comparison operators such as $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin; logical operators $and, $or, $not and $nor; element operators $exists and $type; $regex for patterns; and array operators $all, $size and $elemMatch. For example, db.users.find({ age: { $gte: 18 }, city: { $in: ["Pune", "Delhi"] } }).

6. Which update operators are common, and what is an upsert?

$set sets fields, $unset removes them, $inc increments numbers, $push adds to an array, $addToSet adds only if the value is not already present, $pull removes matching array items and $rename renames a field. With the option { upsert: true }, an update inserts a new document if none matches the filter.

7. How do you project, sort and paginate results?

The second argument to find is a projection that includes or excludes fields, such as { name: 1, email: 1, _id: 0 }. sort({ createdAt: -1 }) sorts descending, and limit and skip paginate. Large skip values are slow, so for big collections paginate with a range on an indexed field, such as createdAt less than the last value seen.

8. What is Mongoose?

Mongoose is a popular library for MongoDB in Node.js that adds schemas, data types, validation, default values, middleware hooks (such as hashing a password before saving), virtual fields, population of references, and model methods. It gives structure to MongoDB's flexible documents, which helps keep data consistent in applications.

9. What is MongoDB Atlas?

Answer flow · 3 steps
  1. Atlas is MongoDB's managed cloud database service on AWS, Azure and Google Cloud.

  2. It handles provisioning, replication, backups, scaling, upgrades and monitoring, and adds features such as Atlas Search (full-text search), Vector Search, Charts and online archive.

  3. It has a free tier, which is popular for learning and small projects.

10. Can MongoDB enforce a schema?

Answer flow · 3 steps
  1. Yes.

  2. Although documents are flexible, a collection can have a validator with a $jsonSchema that defines required fields, types, allowed values and patterns. validationLevel and validationAction decide whether invalid documents are rejected or just logged.

  3. Combined with application-level schemas such as Mongoose, this keeps data clean.

11. How do you query arrays of embedded documents?

A query like { "items.sku": "A1", "items.qty": { $gt: 5 } } can match a document where one item has the SKU and a different item has the quantity. $elemMatch requires both conditions on the same array element: { items: { $elemMatch: { sku: "A1", qty: { $gt: 5 } } } }. The positional $ operator updates the matched element.

Intermediate MongoDB interview questions

Applied problems, trade-offs and questions about your own projects.

12. When do you embed documents and when do you reference them?

Answer flow · 3 steps
  1. I embed when data is accessed together and belongs to one parent, such as order items inside an order or an address inside a user, which allows one-read access.

  2. I reference with IDs when related data is large, grows without limit (such as comments on a viral post), is shared by many documents or changes independently.

  3. Documents have a 16 MB size limit.

13. What is the aggregation pipeline?

The aggregation pipeline processes documents through stages, each transforming the results: $match filters, $group groups and calculates totals, $project reshapes fields, $sort, $limit, $lookup joins another collection, $unwind expands arrays and $facet runs several pipelines at once. Putting $match early lets indexes be used and reduces work.

14. How does indexing work in MongoDB?

Without an index, MongoDB scans every document in the collection. Indexes are B-trees on fields: single-field, compound (where field order follows the equality, sort, range rule), multikey for arrays, text, geospatial, TTL indexes that delete documents after a time, and unique and partial indexes. explain("executionStats") shows whether a query uses an index.

15. Does MongoDB support transactions?

Answer flow · 4 steps
  1. Yes.

  2. Single-document operations have always been atomic, which is why embedding related data is useful.

  3. Since version 4.0 MongoDB supports multi-document ACID transactions on replica sets, and on sharded clusters since 4.2.

  4. Transactions have performance costs, so a good schema should keep most operations to one document.

16. How does $lookup work, and what should you watch out for?

Answer flow · 3 steps
  1. $lookup is an aggregation stage that performs a left outer join with another collection, adding matching documents as an array field, and can use a pipeline for complex conditions.

  2. It is useful but slower than embedded data, especially without an index on the foreign field, and it is limited across sharded collections.

  3. Frequent heavy lookups suggest the schema should embed or duplicate some data.

17. What are write concern, read concern and read preference?

Answer flow · 3 steps
  1. Write concern sets how many replica set members must confirm a write, such as w: "majority" for durability.

  2. Read concern sets the consistency of data read, such as "majority" for data that cannot be rolled back.

  3. Read preference chooses which members serve reads: primary (the default, most current), or secondaries for scaling reads when slightly stale data is acceptable.

18. What is the ESR rule for compound indexes?

Answer flow · 3 steps
  1. Order the fields in a compound index as Equality, then Sort, then Range.

  2. Fields tested for exact matches come first, then fields used for sorting, then fields with range conditions such as $gt or $lt.

  3. Following this rule lets one index both filter efficiently and return results already sorted, avoiding slow in-memory sorts.

19. How do you implement search in MongoDB?

Answer flow · 3 steps
  1. A text index supports basic keyword search with $text and relevance scores, but only one text index per collection is allowed and features are limited.

  2. Atlas Search, built on Apache Lucene, provides proper full-text search with fuzzy matching, autocomplete, facets and relevance tuning through the $search aggregation stage.

  3. Regular expressions without a prefix cannot use indexes efficiently.

20. What are change streams?

Answer flow · 3 steps
  1. Change streams let applications subscribe to real-time changes (inserts, updates, deletes) on a collection, database or whole deployment, using the replica set's operation log.

  2. They are used to sync data to search engines or caches, trigger notifications and build event-driven systems.

  3. A resume token lets a consumer continue from where it stopped after a restart.

21. What is GridFS?

Answer flow · 3 steps
  1. GridFS stores files larger than the 16 MB document limit by splitting them into chunks stored in one collection, with metadata in another.

  2. It lets you keep files in MongoDB with replication and backups.

  3. For most applications, object storage such as S3 with just the file URL saved in MongoDB is cheaper and faster.

22. What MongoDB schema design patterns do you know?

Extended reference (copy frequently needed fields from a related document to avoid lookups), subset (embed only recent or top items, such as the latest 10 reviews), computed (store pre-calculated totals), bucket (group time-series readings into one document per hour), outlier (handle rare huge documents separately), and schema versioning (store a version field to migrate documents gradually).

High level MongoDB interview questions

System design, deep internals, leadership and tough follow-ups.

23. What is a replica set?

Answer flow · 3 steps
  1. A replica set is a group of MongoDB servers holding the same data: one primary that accepts writes and secondaries that replicate its operation log.

  2. If the primary fails, the members elect a new primary automatically.

  3. Write concern controls how many members must confirm a write, and read preference allows reading from secondaries.

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

Answer flow · 4 steps
  1. Sharding distributes data across several replica sets (shards) for horizontal scaling.

  2. A good shard key has high cardinality, distributes writes evenly and matches common query patterns so queries go to one shard.

  3. A monotonically increasing key such as a timestamp sends all new writes to one shard; hashed sharding or a compound key avoids this.

  4. Shard keys can be refined but are hard to change.

25. How would you design a MongoDB schema for an e-commerce app?

I design around access patterns: products with embedded variants and attributes; orders that embed a snapshot of item details, prices and shipping address so history does not change when products do; users with embedded addresses; and reviews in a separate collection referencing the product, with summary fields like average rating stored on the product. I add indexes for the main queries such as category and price.

26. How do you analyse query performance in MongoDB?

Answer flow · 4 steps
  1. Run explain("executionStats") and check the winning plan: IXSCAN means an index was used and COLLSCAN means a full collection scan.

  2. Compare totalDocsExamined and totalKeysExamined with nReturned; ideally they are close.

  3. A covered query, where all fields are in the index and _id is excluded, reads no documents at all.

  4. The database profiler and Atlas Performance Advisor find slow queries and suggest indexes.

27. How do you change a MongoDB schema over time?

Answer flow · 3 steps
  1. Because documents in one collection can have different shapes, add a schemaVersion field and make the application handle both old and new versions.

  2. Migrate documents lazily when they are read or updated, or in background batches, and remove support for old versions once all documents are migrated.

  3. Validators can be updated to require the new structure for new writes.

28. What are time series collections?

Answer flow · 3 steps
  1. Time series collections, added in MongoDB 5.0, are optimised for measurements over time such as sensor readings, metrics and stock prices.

  2. You declare a timeField and metaField, and MongoDB stores data in compressed, column-like buckets automatically, which greatly reduces storage and speeds up time-based queries.

  3. Documents can expire automatically with expireAfterSeconds.

29. How does vector search work in MongoDB?

Atlas Vector Search stores embeddings, arrays of numbers produced by AI models, inside documents and indexes them for approximate nearest-neighbour search. The $vectorSearch aggregation stage finds documents with embeddings most similar to a query embedding, optionally filtered by other fields, which powers semantic search and retrieval-augmented generation alongside normal application data.

30. When would you not choose MongoDB?

When data is highly relational with many-to-many relationships and complex joins, such as accounting or ERP systems; when you need complex multi-table transactions as the main workload; when strict schemas and constraints are essential; or for heavy ad hoc analytics, where a relational database or data warehouse fits better. MongoDB is strong for flexible, document-shaped data accessed by key or simple queries.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a database engineer interview?

See all Database Engineer interview questions, covering SQL, MySQL, PostgreSQL, Oracle, SQL Server and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields