MongoDB and Mongoose Interview Questions for MERN Stack
25 MongoDB and Mongoose questions with answers for mern stack roles — 7 easy, 12 medium, 6 hard.
About MongoDB and Mongoose
MongoDB stores application data as flexible BSON documents, and Mongoose adds schemas, validation and helpers on top of the Node.js driver. This topic covers CRUD operations, data modelling with embedding and referencing, indexes, the aggregation pipeline, transactions, replica sets, sharding and performance tuning with explain. Expect both design questions and query-writing tasks in interviews.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is MongoDB and how is it different from a relational database?
MongoDB is a document database that stores data as flexible JSON-like documents in collections instead of rows in fixed tables. Related data can be embedded in one document, so many reads need no joins. Schemas are flexible, horizontal scaling through sharding is built in, and it supports indexes, aggregation and multi-document ACID transactions. Relational databases fit strongly structured data with many relationships and complex joins.
BSON is the binary format MongoDB uses to store documents. It extends JSON with types like Date, ObjectId, Decimal128, binary data and 32 or 64-bit integers, and is fast to traverse. ObjectId is the default 12-byte _id value made of a 4-byte timestamp, a 5-byte random value and a 3-byte counter. Because it starts with a timestamp, ObjectIds roughly sort by creation time.
03
What are a Mongoose schema and model, and how does validation work?
A schema defines the shape of documents: field types, defaults, required flags, validators, indexes and options like timestamps. A model is compiled from a schema with mongoose.model('User', userSchema) and provides query methods like find, create and updateOne. Built-in validators include required, min, max, enum and match, and you can add custom validators. Validation runs on save and create; for updates, set runValidators: true.
04
A client wants deleted records to be recoverable. How would you implement soft delete with Mongoose?
Add fields like isDeleted: Boolean with default false and deletedAt: Date. The delete endpoint sets these instead of removing the document. Add a pre-find query middleware that filters isDeleted: false by default, and an admin route to restore. Include isDeleted in relevant indexes or use partial indexes, for example a unique email index that only applies to non-deleted users. Purge old records with a scheduled job.
05
Write basic CRUD commands in mongosh for a users collection.
Embed when data is read together, belongs to one parent, and is bounded in size, such as addresses inside a user or line items inside an order. Reference with ObjectIds when the related data is large, grows without limit, is shared by many documents or is updated independently, such as products referenced by many orders. The rule is to design for your application's query patterns, not for normalisation.
09
What is the aggregation pipeline and what are its common stages?
The aggregation pipeline processes documents through a sequence of stages, each transforming the stream. Common stages are $match to filter, $group to aggregate with operators like $sum and $avg, $project or $addFields to shape fields, $sort, $limit, $skip, $lookup to join another collection, $unwind to flatten arrays and $facet for multiple outputs. Put $match and $sort early so they can use indexes and reduce the data volume.
10
What are Mongoose middleware hooks and give a common use case.
Mongoose middleware are functions that run before or after operations such as save, validate, deleteOne, findOneAndUpdate and aggregate. A classic pre-save hook hashes a password only if it was modified: if (!this.isModified('password')) return; this.password = await bcrypt.hash(this.password, 12). Post hooks are used for logging or syncing. Note that query middleware like findOneAndUpdate does not trigger save hooks.
11
What does lean() do in Mongoose and when should you use it?
By default Mongoose queries return full documents with change tracking, getters, virtuals and methods like save. Calling .lean() returns plain JavaScript objects, which uses much less memory and is noticeably faster. Use it for read-only endpoints such as lists and API responses. Skip it when you need to modify and save the document, or depend on virtuals and getters unless you add a lean plugin.
12
A MongoDB query on an orders collection takes 3 seconds. How do you diagnose and fix it?
Run the query with .explain('executionStats') and check whether the winning plan is COLLSCAN and how totalDocsExamined compares to nReturned. Create an index matching the filter and sort, following ESR, and confirm it becomes IXSCAN. Also project only needed fields, add limits, use lean in Mongoose, and check the profiler or Atlas Performance Advisor for other slow queries. Re-test with production-like data volume.
13
Duplicate user accounts with the same email are being created even though the code checks for an existing email first. Why, and how do you fix it?
Check-then-insert is a race condition: two concurrent requests both see no user and both insert. The real fix is a unique index on email, normalised to lowercase, so the database rejects the second insert with error code 11000. Catch that error and return 409 Conflict. Clean up existing duplicates before building the index, otherwise index creation fails.
14
The business wants total sales per category for the last 30 days. How would you build it in MongoDB?
Use an aggregation pipeline: $match orders with status paid and createdAt in the last 30 days, using an index on createdAt; $unwind the items array; $group by items.category summing items.price times items.qty; then $sort by total descending. If the report is viewed often, precompute daily totals into a summary collection with a scheduled job or $merge, so the dashboard reads small documents.
15
Write an aggregation that counts orders and sums revenue per status.
Query: orders of one user, newest first.
db.orders.createIndex({ userId: 1, createdAt: -1 })
db.orders.find({ userId: ObjectId('...') })
.sort({ createdAt: -1 })
.limit(20)
.explain('executionStats')
Check that the winning plan shows IXSCAN, not COLLSCAN, and that totalDocsExamined is close to nReturned. In Mongoose, declare it with orderSchema.index({ userId: 1, createdAt: -1 }).
17
Show the use of $push, $addToSet, $inc and $pull update operators.
Situation: our admin orders page took 8 seconds to load. Task: I was asked to fix it within a sprint. Action: I profiled the API, found a populate on every row plus an unindexed sort, added a compound index, replaced populate with a single $lookup projecting only needed fields, and used lean. Result: load time dropped below 600 ms and I shared an indexing checklist with the team.
19
Describe a mistake you made with data and how you handled it.
Situation: I ran an update script against the staging database with a wrong filter and modified thousands of records. Task: restore data before QA testing next morning. Action: I informed my lead immediately, restored from the nightly backup, re-applied the day's valid changes, and then added a dry-run mode and a count confirmation step to our scripts. Result: QA was not blocked, and no similar incident happened again.
20
Explain indexes in MongoDB, compound indexes and the ESR rule.
An index is a sorted structure that lets queries avoid scanning every document. A compound index covers multiple fields in order, like { userId: 1, createdAt: -1 }, and supports queries on its leading prefix. The ESR guideline says order fields as Equality first, then Sort, then Range. Indexes speed reads but slow writes and use memory, so create them for real query patterns and drop unused ones.
21
What is the difference between Mongoose populate and the $lookup aggregation stage?
populate is a Mongoose feature that replaces ObjectId references with documents by running extra queries from the application. It is convenient and readable but issues additional round trips. $lookup is a server-side join inside the aggregation pipeline, which can also filter, project and combine with grouping in one query. Use populate for simple CRUD views and $lookup for reports or when you need to filter on joined data.
22
How do transactions work in MongoDB and when do you need them?
Single-document writes are already atomic, so good embedded design avoids most transactions. Multi-document ACID transactions are available on replica sets and sharded clusters, not on a standalone server. In Mongoose, start a session, call session.withTransaction() and pass the session to every operation. Use them for cases like transferring wallet balance between two users. They add latency and should stay short, ideally under one second.
23
What are replica sets and sharding in MongoDB, and how do you choose a shard key?
A replica set is a primary plus secondaries holding copies of data, giving automatic failover and optional read scaling. Sharding splits a collection across multiple shards for horizontal scaling of data size and write throughput. A good shard key has high cardinality, evenly distributed writes and matches common queries so they target one shard. Monotonic keys like createdAt create hot spots unless hashed.
24
You stored all comments inside each blog post document and some posts are now very large. How would you redesign it?
An unbounded embedded array risks hitting the 16 MB document limit and makes every post read and update heavy. Move comments to their own collection with a postId field and an index on { postId: 1, createdAt: -1 }, then paginate. Optionally keep a small embedded array of the latest few comments plus a commentCount on the post for fast first render. This is the subset pattern.
25
You need to rename a field and change its type across 20 million documents in production. How do you do it safely?
Avoid a single big blocking update. Make the application read both old and new formats first, then run a batched migration script that processes documents in chunks by _id range with bulkWrite, throttled and resumable, or an updateMany with an aggregation pipeline during low traffic. Track progress, verify counts, back up first, then remove the old-field handling in a later release.
Frequently asked questions
How important is MongoDB and Mongoose in MERN Stack interviews?
MongoDB stores application data as flexible BSON documents, and Mongoose adds schemas, validation and helpers on top of the Node.js driver. This topic covers CRUD operations, data modelling with embedding and referencing, indexes, the aggregation pipeline, transactions, replica sets, sharding and performance tuning with explain. Expect both design questions and query-writing tasks in interviews.
How should I use the MongoDB and Mongoose sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.