MongoDB Interview Questions
20 questions with detailed answers
Q1. What is MongoDB and how does it differ from relational databases?
Answer: MongoDB is a document-oriented NoSQL database storing BSON documents in collections. Unlike SQL tables with fixed schemas and joins, MongoDB uses flexible documents, favors embedding over joins, and scales horizontally with sharding.
Q2. What is BSON?
Answer: BSON (Binary JSON) is MongoDB's storage format — a binary-encoded superset of JSON supporting additional types like Date, ObjectId, int64, and Decimal128.
Q3. Explain the difference between find() and aggregate().
Answer: find() returns documents matching a filter as stored. aggregate() runs a pipeline of stages ($match, $group, $lookup) to filter, transform, join, and compute analytics in the database.
Q4. When would you embed vs reference data?
Answer: Embed when data is accessed together and has one-to-few cardinality (order line items). Reference with ObjectId when data is large, shared across documents, or updated independently (user profile referenced by orders).
Q5. What is the purpose of an index in MongoDB?
Answer: Indexes are B-tree structures that let queries locate documents without scanning the entire collection. They speed reads but add overhead on writes.
Q6. What is the ESR rule for compound indexes?
Answer: Equality fields first, Sort fields second, Range fields last. Example: { status: 1, createdAt: -1, price: 1 } for filtering by status, sorting by date, and ranging on price.
Q7. Difference between updateOne and replaceOne?
Answer: updateOne applies update operators ($set, $inc) to specific fields. replaceOne replaces the entire document (except _id) with the new document provided.
Q8. What does $lookup do?
Answer: $lookup performs a left outer join — for each input document, it looks up matching documents in another collection and adds them to an array field.
Q9. What is a replica set?
Answer: A replica set is a group of MongoDB servers maintaining the same data. One primary handles writes; secondaries replicate for redundancy and optional read scaling.
Q10. Does MongoDB support ACID transactions?
Answer: Yes, since MongoDB 4.0, multi-document ACID transactions are supported on replica sets. Use sessions and withTransaction for operations that must succeed or fail together.
Q11. What is NoSQL injection and how do you prevent it?
Answer: Attackers pass crafted objects as query filters (e.g. { $gt: '' }). Prevent by validating input types, using schema validation, never passing raw user objects to queries, and using parameterized driver methods.
Q12. Explain $elemMatch.
Answer: $elemMatch matches array elements that satisfy multiple conditions on the same element. Example: items: { $elemMatch: { qty: { $gt: 5 }, price: { $lt: 100 } } }.
Q13. What is the difference between deleteOne and drop()?
Answer: deleteOne/deleteMany remove matching documents but keep the collection and indexes. drop() removes the entire collection including its indexes.
Q14. What is Mongoose?
Answer: Mongoose is an ODM for Node.js that defines schemas, validation, middleware hooks, and a model API on top of the MongoDB driver.
Q15. What is a TTL index?
Answer: A TTL (Time To Live) index automatically deletes documents after a specified seconds-to-live on a date field — useful for sessions, logs, and cache entries.
Q16. What is the maximum document size?
Answer: 16 megabytes per document. Larger files use GridFS which splits files into chunks stored across documents.
Q17. Difference between $push and $addToSet?
Answer: $push appends a value to an array. $addToSet adds only if the value is not already present — like a set.
Q18. What does explain('executionStats') show?
Answer: It shows the query plan: whether IXSCAN or COLLSCAN was used, documents examined vs returned, execution time — essential for index tuning.
Q19. What is sharding?
Answer: Sharding distributes data across multiple servers (shards) by a shard key. It enables horizontal scaling when a single replica set cannot hold or serve the dataset.
Q20. What is a capped collection?
Answer: A fixed-size collection that automatically overwrites oldest documents when full — used for logs and queues with FIFO behavior.