MongoDB Interview Prep
Everything a fresher or junior developer needs for MongoDB interviews, in simple English: concepts, code, gotchas, and the questions interviewers really ask.
What is MongoDB?
A document database that stores data as flexible JSON-like documents instead of rows and tables.
MongoDB is a NoSQL document database. Instead of tables with fixed columns, you store documents (like JSON objects) inside collections. Each document can have its own shape. It is built for easy scaling (sharding) and high availability (replica sets).
// One document in a "users" collection
{
_id: ObjectId("66f1a2b3c4d5e6f708192a3b"),
name: "Danish",
skills: ["React", "Node", "MongoDB"],
address: { city: "Peshawar", country: "PK" },
createdAt: ISODate("2026-11-27T10:00:00Z")
}
SQL words vs MongoDB words
| SQL | MongoDB | Note |
|---|---|---|
| Database | Database | Same idea |
| Table | Collection | A group of documents |
| Row | Document | One record |
| Column | Field | Can be different per document |
| Primary key | _id |
Added automatically |
| JOIN | $lookup or embedding |
Embedding is preferred |
| GROUP BY | Aggregation pipeline | $group stage |
| Index | Index | Same idea (B-tree) |
When MongoDB is a good choice
- Data shape changes often (startups, fast product changes)
- Data is naturally nested: products with variants, posts with comments
- High write volume, big data, or you need to scale out (sharding)
- Content management, catalogs, user profiles, real-time apps, IoT, logs
When to be careful
- Data is very relational with many joins everywhere (banking ledgers, ERP)
- You need strict constraints between many tables (foreign keys)
- Many reports that join 5+ entities (SQL can be simpler)
Interview focus
"Why MongoDB over SQL?" Good answer: "Flexible schema, JSON-like documents that match my code objects, easy horizontal scaling, and embedded documents let me read related data in one query. I would still choose SQL when the data is highly relational and needs strong cross-table integrity." Never say "MongoDB is always better".
Documents, Collections & ObjectId
The building blocks, and what is inside `_id`.
Rules of a document
- Max size is 16 MB per document (use GridFS for bigger files)
- Max nesting depth is 100 levels
- Every document has a unique, immutable
_id(added for you if missing) - Field names are case-sensitive; field order is kept
- Databases and collections are created lazily on the first insert
What is ObjectId?
ObjectId is a 12-byte value, shown as 24 hex characters.
| Part | Size | Meaning |
|---|---|---|
| Timestamp | 4 bytes | Seconds since Unix epoch |
| Random value | 5 bytes | Unique per process |
| Counter | 3 bytes | Starts random, goes up by 1 |
Because it starts with the time, ids are roughly sorted by creation time, and no central counter is needed. Each app server can create ids on its own.
const id = new ObjectId();
id.getTimestamp(); // creation date, free createdAt!
id.toString(); // "66f1a2b3c4d5e6f708192a3b"
// Querying by id: you MUST convert the string
db.users.findOne({ _id: ObjectId("66f1a2b3c4d5e6f708192a3b") });
db.users.findOne({ _id: "66f1a2b3c4d5e6f708192a3b" }); // returns null (string != ObjectId)
Common bug
Comparing a string id with an ObjectId returns nothing. Mongoose converts for you (findById), the raw driver does not.
Interview focus
- "What is inside an ObjectId?" → timestamp + random + counter (12 bytes).
- "Can I use my own
_id?" → Yes (string, number, UUID). It must be unique and cannot be changed. - "Is ObjectId safe as a shard key?" → As a ranged key no, it always increases (hot shard). Use hashed.
BSON & Data Types
MongoDB stores BSON, a fast binary form of JSON with extra types.
BSON = Binary JSON. It is not human readable, but it is fast to scan, stores the length of fields, and adds types JSON does not have (Date, ObjectId, Decimal128, binary).
| Type | Example | Notes |
|---|---|---|
| String | "hello" |
UTF-8 |
| Int32 / Int64 | NumberInt(5) / NumberLong(5) |
Whole numbers |
| Double | 3.14 |
Floating point |
| Decimal128 | NumberDecimal("19.99") |
Use for money |
| Boolean | true |
|
| Date | ISODate("2026-11-27") |
Stored in UTC as milliseconds |
| ObjectId | ObjectId() |
12 bytes |
| Array | [1, 2, 3] |
Can hold mixed types |
| Embedded document | { a: 1 } |
Nested object |
| Null | null |
|
| BinData | binary | Files, hashes, UUID |
Type matters in queries
{ age: 25 } does not match a document where age is the string "25". Keep one type per field. Mongoose schemas help with this.
Money
Never store money as floating-point (0.1 + 0.2 != 0.3). Use Decimal128, or store the smallest unit as an integer (cents / paisa).
CRUD Operations
Create, Read, Update, Delete: the daily commands.
Create
db.users.insertOne({ name: "Ali", age: 22 });
// { acknowledged: true, insertedId: ObjectId("...") }
db.users.insertMany([{ name: "Sara" }, { name: "Omar" }], { ordered: false });
// ordered:true (default) stops at the first error; false keeps going
Read
db.users.find({ age: { $gte: 18 } }); // cursor (many docs)
db.users.findOne({ name: "Ali" }); // one doc or null
db.users.find({}, { name: 1, _id: 0 }); // projection: only name
db.users.find().sort({ age: -1 }).skip(10).limit(5);
db.users.countDocuments({ age: { $gte: 18 } }); // accurate count
Update
db.users.updateOne({ name: "Ali" }, { $set: { age: 23 } });
db.users.updateMany({ city: "Lahore" }, { $inc: { visits: 1 } });
db.users.replaceOne({ name: "Ali" }, { name: "Ali", age: 30 }); // replaces whole doc (keeps _id)
db.users.updateOne({ email: "a@x.com" }, { $set: { name: "A" } }, { upsert: true });
db.users.findOneAndUpdate({ _id: id }, { $inc: { stock: -1 } }, { returnDocument: "after" });
Delete
db.users.deleteOne({ name: "Ali" });
db.users.deleteMany({ active: false });
db.users.drop(); // removes whole collection (fast, also removes indexes)
What each method returns
| Method | Result |
|---|---|
insertOne |
{ acknowledged, insertedId } |
insertMany |
{ acknowledged, insertedIds } |
updateOne/Many |
{ matchedCount, modifiedCount, upsertedId } |
deleteOne/Many |
{ deletedCount } |
findOne |
document or null |
find |
cursor (lazy, fetches in batches) |
Interview focus
updateOnewith$setchanges fields;replaceOnereplaces the whole document.matchedCountcan be 1 whilemodifiedCountis 0 (value was already the same).findOneAndUpdateis atomic: find and update in one step (great for counters, queues, stock).sort,skip,limitalways run in this order: sort → skip → limit, no matter how you chain them.
Query Operators
Filter documents with comparison, logical, array and element operators.
| Group | Operators | Example |
|---|---|---|
| Comparison | $eq $ne $gt $gte $lt $lte $in $nin |
{ age: { $gt: 18, $lt: 60 } } |
| Logical | $and $or $nor $not |
{ $or: [{ a: 1 }, { b: 2 }] } |
| Element | $exists $type |
{ phone: { $exists: true } } |
| Array | $all $elemMatch $size |
{ tags: { $all: ["js", "db"] } } |
| Evaluation | $regex $expr $text $mod |
{ name: /^Al/i } |
Multiple conditions in one object are an implicit AND:
db.users.find({ city: "Lahore", age: { $gte: 18 } }); // city AND age
db.users.find({ $or: [{ city: "Lahore" }, { city: "Karachi" }] });
db.users.find({ city: { $in: ["Lahore", "Karachi"] } }); // shorter than $or for one field
Nested fields and arrays
db.users.find({ "address.city": "Peshawar" }); // dot notation (needs quotes)
db.users.find({ skills: "React" }); // array contains "React"
db.users.find({ skills: ["React"] }); // array EQUALS exactly ["React"]
$elemMatch: the classic trap
// order = { items: [ { sku: "A1", qty: 1 }, { sku: "B2", qty: 9 } ] }
// WRONG idea: can match different elements (A1 from one, qty 9 from another)
db.orders.find({ "items.sku": "A1", "items.qty": { $gt: 5 } }); // matches!
// RIGHT: both conditions must be true for the SAME array element
db.orders.find({ items: { $elemMatch: { sku: "A1", qty: { $gt: 5 } } } }); // no match
null vs missing
{ phone: null } matches documents where phone is null or does not exist. To match only real nulls, add { $type: "null" }; to check missing only, use { $exists: false }.
Interview focus
$invs$or: same result for one field,$inis simpler and index-friendly.- Regex:
/^abc/(anchored at start) can use an index;/abc/scans everything. find()returns a cursor; nothing runs until you iterate (toArray(),for await).
Update Operators & Arrays
Change fields in place without rewriting the whole document.
| Operator | What it does |
|---|---|
$set / $unset |
Set a field / remove a field |
$inc / $mul |
Add / multiply a number (atomic) |
$min / $max |
Update only if new value is smaller / bigger |
$rename |
Rename a field |
$currentDate |
Set to now |
$setOnInsert |
Set only when an upsert inserts |
$push |
Add item to an array ($each, $slice, $sort modifiers) |
$addToSet |
Add only if not already there (no duplicates) |
$pull |
Remove items matching a condition |
$pop |
Remove first (-1) or last (1) item |
db.users.updateOne({ _id }, { $push: { logins: { $each: [new Date()], $slice: -10 } } }); // keep last 10
db.users.updateOne({ _id }, { $addToSet: { tags: "vip" } });
db.users.updateOne({ _id }, { $pull: { tags: "trial" } });
Updating one element inside an array
// order.items = [ { sku: "A1", qty: 1 }, { sku: "B2", qty: 2 } ]
// positional $ : first element that matched the query
db.orders.updateOne({ _id, "items.sku": "B2" }, { $set: { "items.$.qty": 5 } });
// $[] : ALL elements
db.orders.updateOne({ _id }, { $inc: { "items.$[].qty": 1 } });
// $[x] + arrayFilters : elements that match a filter
db.orders.updateOne({ _id }, { $set: { "items.$[i].qty": 0 } }, { arrayFilters: [{ "i.sku": "A1" }] });
Upsert + atomic counters
db.pageViews.updateOne(
{ page: "/home" },
{ $inc: { views: 1 }, $setOnInsert: { createdAt: new Date() } },
{ upsert: true }
);
Atomic stock decrement
Put the check inside the filter so two buyers cannot both win:
updateOne({ _id, stock: { $gte: qty } }, { $inc: { stock: -qty } }) and check modifiedCount === 1.
Interview focus
- Single-document updates are atomic: no one sees half of the change.
$pushvs$addToSet: duplicates allowed vs not.- Since 4.2 you can update with an aggregation pipeline (
updateOne(filter, [ {$set: {...}} ])) to use other fields in the same document.
Data Modeling: Embed vs Reference
The most asked MongoDB design question.
Rule 1: design for how your app reads and writes the data, not for how the data looks on paper.
| Question | Embed | Reference |
|---|---|---|
| Read together almost always? | Yes | No |
| Child has its own life / used alone? | No | Yes |
| How many children? | Few (tens) | Many (thousands+) |
| Child changes often? | Rarely | Often |
| Child shared by many parents? | No | Yes |
| Need atomic update of both? | Yes (one doc) | Needs a transaction |
Examples
// EMBED: address belongs to one user, always read with the user
{ _id: 1, name: "Ali", address: { city: "Lahore", street: "Mall Road" } }
// REFERENCE: orders belong to a user but there can be thousands
{ _id: 1, name: "Ali" }
{ _id: 901, userId: 1, total: 4500 } // many orders point to user 1
Relationship cheat sheet
- One-to-one: embed.
- One-to-few (addresses, phone numbers): embed an array.
- One-to-many (orders of a user): reference from the "many" side (
userIdon the order). - One-to-squillions (logs, events, chat messages): reference, and think about buckets.
- Many-to-many (students ↔ courses): array of ids on one or both sides.
Useful design patterns
| Pattern | Idea |
|---|---|
| Subset | Embed only the latest/most-used items (last 10 reviews), keep the rest in another collection |
| Extended reference | Copy a few fields you always need (author name) next to the reference |
| Bucket | Group many small records into one doc per hour/day (IoT, logs) |
| Computed | Store pre-calculated values (commentCount, avgRating) |
| Schema versioning | Add schemaVersion so old and new shapes can live together |
| Polymorphic | Different shapes in one collection with a type field |
Anti-patterns
- Unbounded arrays: a comments array that grows forever will hit 16 MB and slow every update.
- Giant documents you only need 5% of.
- Joining everywhere with
$lookup: it means you modelled it like SQL. - Over-duplicating data that changes often (hard to keep in sync).
Interview focus
"Embed or reference?" Answer with questions: Read together? How many? Does the child grow without limit? Does it change a lot? Is it shared? Then give an example. This shows you think about access patterns.
Indexes
Make queries fast, at a cost of space and slower writes.
Without an index MongoDB does a collection scan (COLLSCAN): it reads every document. An index is a B-tree of field values that points to documents, so lookups are fast. _id always has a unique index.
db.orders.createIndex({ userId: 1 }); // single field
db.orders.createIndex({ userId: 1, createdAt: -1 }); // compound
db.users.createIndex({ email: 1 }, { unique: true }); // unique
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); // TTL
db.users.createIndex({ phone: 1 }, { partialFilterExpression: { phone: { $exists: true } } });
db.orders.getIndexes();
db.orders.dropIndex("userId_1");
Index types
| Type | Use |
|---|---|
| Single field | Filter or sort on one field |
| Compound | Several fields; order matters |
| Multikey | Index on an array field (one entry per element) |
| Unique | No duplicates (emails, usernames) |
| TTL | Auto-delete old docs (sessions, OTPs); a background job runs about every 60 seconds |
| Partial / Sparse | Index only some documents (saves space) |
| Text | Basic text search (one per collection). For real search use Atlas Search |
| 2dsphere | Geo queries ("near me") |
| Hashed | Even distribution, used for hashed sharding |
| Wildcard | Many unknown field names |
Compound index: prefix rule
An index on { a: 1, b: 1, c: 1 } supports queries on a, a+b, and a+b+c. It does not help a query on only b or only c.
The ESR rule
Order fields in a compound index as: Equality → Sort → Range.
// Query
db.orders.find({ status: "paid", total: { $gt: 100 } }).sort({ createdAt: -1 });
// Best index (Equality: status, Sort: createdAt, Range: total)
db.orders.createIndex({ status: 1, createdAt: -1, total: 1 });
Reading explain()
db.orders.find({ userId: 7 }).explain("executionStats");
| Look at | Good | Bad |
|---|---|---|
winningPlan.stage |
IXSCAN (+ FETCH) |
COLLSCAN |
totalDocsExamined vs nReturned |
Close to each other | Examined is huge, returned is tiny |
totalKeysExamined |
Small | Very large |
| Sort stage | Uses index order | In-memory SORT stage |
Covered query
If every field in the filter and the projection is in the index (and you exclude _id or it is in the index), MongoDB answers from the index alone: no document fetch, very fast (totalDocsExamined: 0).
Costs of indexes
Every insert/update/delete must also update every index, and indexes use RAM and disk. Add indexes for real queries only. Check unused ones with $indexStats.
Interview focus
- Explain ESR with an example.
- Why is
{ name: /abc/ }slow? (not anchored, cannot use the B-tree range) - Multikey limit: a compound index cannot have two array fields in the same document.
- A sort without a matching index happens in memory. It has a memory limit (100 MB per sort in older versions; newer versions can spill to disk), so index the sort field.
Aggregation Pipeline
Process data in stages: filter, group, reshape, join, sort.
Documents flow through a pipeline. Each stage takes the output of the previous stage.
// Top 3 customers by money spent on paid orders
db.orders.aggregate([
{ $match: { status: "paid" } }, // 1. filter early
{ $group: { _id: "$userId", total: { $sum: "$total" }, orders: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 3 },
{ $lookup: { from: "users", localField: "_id", foreignField: "_id", as: "user" } },
{ $unwind: "$user" },
{ $project: { _id: 0, name: "$user.name", total: 1, orders: 1 } }
]);
Important stages
| Stage | Job |
|---|---|
$match |
Filter (like find). Put it first so it can use an index |
$group |
Group by a key and calculate ($sum $avg $min $max $push $addToSet $first $last) |
$project |
Choose / rename / calculate fields |
$addFields / $set |
Add fields, keep the rest |
$sort, $limit, $skip |
Order and page |
$unwind |
Turn an array into one document per element |
$lookup |
Left outer join with another collection |
$count |
Count documents |
$facet |
Run several pipelines at once (e.g. results + total count) |
$bucket |
Group into ranges (price bands) |
$out / $merge |
Write the result to a collection |
More examples
// Revenue per month
db.orders.aggregate([
{ $group: { _id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } }, revenue: { $sum: "$total" } } },
{ $sort: { _id: 1 } }
]);
// Total of everything: use _id: null
db.orders.aggregate([{ $group: { _id: null, total: { $sum: "$total" } } }]);
// Quantity sold per product (array of items)
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: { _id: "$items.sku", qty: { $sum: "$items.qty" } } }
]);
Speed tips
$matchand$projectearly to shrink data.$match/$sortat the start can use indexes. After$groupor$projectthey cannot.$sort+$limittogether are optimised (only the top N is kept).$lookupneeds an index on theforeignFieldin the other collection.- Blocking stages (
$group,$sort) use memory (100 MB per stage in older versions). UseallowDiskUsefor big data; newer versions can spill to disk by default.
Interview focus
findvsaggregate:findfilters;aggregatecan also group, join, and compute.$projectvs$addFields: project defines the output shape; addFields keeps everything and adds.$lookupis a left outer join, but it is not as cheap as a SQL join, so prefer good modelling.- Map-reduce is deprecated; use aggregation.
Transactions & ACID
Atomic by default for one document; multi-document transactions when you need them.
- A write to one document (even with nested arrays) is always atomic. Good modelling often removes the need for transactions.
- Since 4.0 you can use multi-document ACID transactions on replica sets, and since 4.2 on sharded clusters.
- A transaction needs a replica set (even a single-node replica set for local dev).
// Transfer money between two accounts (Node driver)
const session = client.startSession();
try {
await session.withTransaction(async () => {
const accounts = client.db("bank").collection("accounts");
const r = await accounts.updateOne(
{ _id: from, balance: { $gte: amount } },
{ $inc: { balance: -amount } },
{ session }
);
if (r.modifiedCount !== 1) throw new Error("Not enough balance");
await accounts.updateOne({ _id: to }, { $inc: { balance: amount } }, { session });
});
} finally {
await session.endSession();
}
withTransaction also retries automatically on transient errors. Every operation must receive { session }.
Things to remember
- Default time limit: 60 seconds per transaction. Keep them short.
- They use snapshot isolation. A conflicting write makes one transaction abort (
WriteConflict). - They cost performance and hold locks/resources. Use them for real multi-document invariants only.
- Mongoose:
const session = await mongoose.startSession(); await session.withTransaction(async () => { await Order.create([data], { session }); ... }).
Interview focus
"Does MongoDB support ACID?" Yes. Single-document operations are always ACID. Multi-document transactions are supported (4.0+ replica sets, 4.2+ sharded) but you should model data so you rarely need them.
Replication & Replica Sets
Copies of your data on several servers for safety and uptime.
A replica set is a group of mongod servers holding the same data.
- Primary: the only node that accepts writes (by default also reads).
- Secondaries: copy the primary's changes by reading its oplog (a capped collection of every write).
- Up to 50 members, but only 7 can vote.
- Nodes send heartbeats every 2 seconds. If the primary is silent for ~10 seconds, an election starts. A node needs a majority of votes to become primary.
- Use an odd number of voting members (3 is the minimum for real failover).
- An arbiter votes but holds no data. Prefer a real data-bearing member instead.
rs.status(); // health of each member
rs.conf(); // configuration (priority, votes, hidden...)
Read preference (where reads go)
| Mode | Reads from |
|---|---|
primary (default) |
Primary only: always fresh |
primaryPreferred |
Primary, secondary if primary is down |
secondary |
Secondaries only (may be slightly stale) |
secondaryPreferred |
Secondary, primary if none |
nearest |
Lowest network latency |
Stale reads
Secondaries can lag. Reading your own just-written data from a secondary can return old data. Reading from the primary avoids that.
Why use replication?
High availability (automatic failover), data safety, backups from a secondary, read scaling for analytics. It does not make writes faster, that is sharding.
Interview focus
- Walk through a failover: primary dies → heartbeats stop → secondaries hold an election → one gets majority → driver finds the new primary and retries.
- Why 3 nodes not 2? With 2 nodes, if one dies the other cannot get a majority.
- Rollback: if the old primary had writes that were not replicated, those writes are rolled back when it rejoins.
w: "majority"prevents this.
Sharding
Split data across many servers to scale horizontally.
Replication copies the same data. Sharding splits different data across shards. Use it when one server cannot hold the data or handle the load, and vertical scaling (bigger machine) is no longer enough.
Components
| Part | Job |
|---|---|
| Shard | Holds a part of the data (usually its own replica set) |
| mongos | Router. The app talks to it. It sends queries to the right shard(s) |
| Config servers | Replica set that stores cluster metadata (which chunk is where) |
Data is split into chunks (default max size 128 MB) by shard-key ranges. A balancer moves chunks to keep shards even.
sh.enableSharding("shop");
sh.shardCollection("shop.orders", { userId: "hashed" });
Choosing a shard key (very important)
A good shard key has:
- High cardinality: many different values.
- Low frequency: no single value is very common.
- Not monotonically increasing: a key like
createdAtor plainObjectIdsends all new writes to the last shard (hot shard). - Matches your queries: so queries go to one shard (targeted), not all (scatter-gather).
| Ranged | Hashed | |
|---|---|---|
| Range queries | Efficient (data stays together) | Scatter-gather |
| Write spread | Can create hot shard if key increases | Even |
| Use when | Queries by ranges, good key | Monotonic keys, even writes |
Shard key notes
Choose carefully. Since 4.2 you can change a document's shard key value, and since 5.0 you can reshard a collection, but it is still heavy work. A chunk that cannot be split (one key value is too big) becomes a jumbo chunk.
Interview focus
- Replication = availability. Sharding = scale. Real clusters use both: each shard is a replica set.
- "How do you pick a shard key?" → cardinality, frequency, monotonic change, query pattern.
- Queries without the shard key go to all shards (slow at scale).
Write Concern, Read Concern & Consistency
How safe vs how fast each operation is.
Write concern: when is a write "done"?
| Setting | Meaning |
|---|---|
w: 1 |
Primary has written it (fast, can be lost if primary dies before replicating) |
w: "majority" |
Most voting nodes have it (safe from rollback). Default since MongoDB 5.0 |
w: 0 |
Fire and forget (no confirmation) |
j: true |
Wait until written to the on-disk journal |
wtimeout |
Max time to wait for the concern |
db.orders.insertOne({ total: 100 }, { writeConcern: { w: "majority", j: true } });
Read concern: how safe is the data you read?
| Level | Meaning |
|---|---|
local (default) |
Latest data on that node (may be rolled back later) |
majority |
Only data acknowledged by a majority |
snapshot |
Consistent snapshot (used in transactions) |
linearizable |
Strongest: reflects all majority-acked writes before the read (slow, primary only) |
Simple memory trick
Write concern = durability of writes. Read concern = safety of reads. Read preference = where reads go. Three different knobs.
CAP theorem
During a network partition you must choose Consistency or Availability. MongoDB is usually described as CP: the side of the partition without a majority cannot accept writes (it steps down), so data stays consistent.
Storage Engine & How MongoDB Works Inside
WiredTiger, journaling, cache and the query planner.
- WiredTiger has been the default engine since 3.2.
- Document-level concurrency: many writers can work on different documents at the same time (MVCC).
- Compression: collections use Snappy by default (zstd/zlib are options); indexes use prefix compression.
- Cache: by default the larger of 50% of (RAM − 1 GB) or 256 MB. The rest of RAM is used by the OS file cache.
- Journal + checkpoints: every write goes to the journal (write-ahead log), and a checkpoint writes a consistent snapshot to disk about every 60 seconds. After a crash, MongoDB restores the last checkpoint and replays the journal.
Working set
The working set is the data and indexes you use often. If it fits in RAM, queries are fast. If not, disk reads make everything slow. This is a common cause of "it was fast, now it's slow".
Query planner
When a query can use several indexes, MongoDB runs the candidate plans for a short trial, picks the winner, and stores it in the plan cache for similar queries (same "shape").
db.orders.find({ status: "paid" }).hint({ status: 1 }); // force an index (use only to debug)
Interview focus
- What does the journal do? (durability and crash recovery)
- What is the oplog? (a capped collection
local.oplog.rsused for replication) - Why does a big working set hurt? (disk reads instead of RAM)
Schema Validation
Rules for documents, enforced by the database.
MongoDB is flexible, not schema-less. You can add rules with $jsonSchema.
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "name"],
properties: {
email: { bsonType: "string", pattern: "^.+@.+$" },
name: { bsonType: "string", minLength: 2 },
age: { bsonType: "int", minimum: 0, maximum: 120 }
}
}
},
validationLevel: "strict", // "moderate" skips existing invalid docs on update
validationAction: "error" // "warn" only logs
});
validationLevel:strict(all inserts/updates) ormoderate(only valid existing docs are checked on update).validationAction:error(reject) orwarn(log only).
Two layers
Use Mongoose validation for friendly errors in your API and DB validation as a safety net for scripts, other services and manual edits.
Mongoose for MERN
The ODM most Node.js apps use.
Mongoose is an ODM (Object Data Modeling) library. It adds schemas, validation, middleware, and helpful query methods on top of the MongoDB driver.
import mongoose from "mongoose";
await mongoose.connect(process.env.MONGO_URI); // connect ONCE at app start
mongoose.connection.on("error", (e) => console.error("DB error", e));
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true, trim: true, minlength: 2 },
email: { type: String, required: true, unique: true, lowercase: true },
password: { type: String, required: true, select: false }, // hidden by default
role: { type: String, enum: ["user", "admin"], default: "user" },
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }]
},
{ timestamps: true } // createdAt + updatedAt
);
userSchema.index({ role: 1, createdAt: -1 });
userSchema.virtual("initials").get(function () { return this.name.slice(0, 2).toUpperCase(); });
userSchema.pre("save", async function (next) { // middleware (hook)
if (this.isModified("password")) this.password = await bcrypt.hash(this.password, 10);
next();
});
export const User = mongoose.model("User", userSchema);
Everyday queries
const user = await User.create({ name: "Ali", email: "ali@x.com", password: "123456" });
const found = await User.findById(id).select("name email");
const list = await User.find({ role: "user" }).sort({ createdAt: -1 }).limit(20).lean();
const updated = await User.findByIdAndUpdate(id, { name: "Ali K" }, { new: true, runValidators: true });
await User.deleteOne({ _id: id });
const post = await Post.findById(postId).populate("author", "name email"); // "join"
Gotchas interviewers love
| Gotcha | Fix |
|---|---|
findByIdAndUpdate returns the old document |
Pass { new: true } |
| Validators do not run on updates by default | Pass { runValidators: true } |
unique: true is an index, not a validator |
Handle error code 11000 (duplicate key) |
populate() runs extra queries (not a DB join) |
Use $lookup or denormalise for heavy cases |
| Full Mongoose documents are heavy | Use .lean() for read-only data (plain JS objects) |
| Unique index not built yet in tests | Call Model.init() or syncIndexes() |
| Connecting inside every request | Connect once, reuse the connection pool |
NoSQL injection
Never pass req.body straight into a filter. { email, password: { "$ne": null } } logs in without a password. Validate types (zod / joi), and consider mongoose.set("sanitizeFilter", true).
Interview focus
populatevs$lookup: populate = extra queries in Node;$lookup= one aggregation on the server.- What does
lean()do and when do you not use it? (You lose virtuals, methods andsave().) - Where do you put business logic: schema methods/statics, hooks, or service layer?
Performance & Best Practices
A checklist you can say out loud in an interview.
- Index for your real queries and check them with
explain("executionStats"). - Project only fields you need. Do not send big documents to the client.
- Paginate properly (see below). Always
limit. - Avoid unbounded arrays and giant documents.
- Use
bulkWrite/insertManyfor batches instead of many single calls. - Use
.lean()in Mongoose for read-heavy endpoints. - Reuse one connection pool (default max pool size is 100 in modern drivers).
- Avoid
$whereand JavaScript in queries. Avoid unanchored regex on big collections. - Keep the working set in RAM; watch memory and cache usage.
- Find slow queries with the profiler or Atlas Performance Advisor.
Pagination: skip vs range
// skip/limit: the server still walks past all skipped docs, so page 5000 is slow
db.posts.find().sort({ _id: -1 }).skip(100000).limit(20);
// range (keyset) pagination: pass the last _id you saw, always fast with an index
db.posts.find({ _id: { $lt: lastSeenId } }).sort({ _id: -1 }).limit(20);
Find slow queries
db.setProfilingLevel(1, { slowms: 100 }); // log operations slower than 100 ms
db.system.profile.find().sort({ ts: -1 }).limit(5);
db.currentOp(); // what is running right now
Slow query playbook (great interview answer)
- Find it (profiler / logs). 2.
explain("executionStats"). 3. COLLSCAN or bigtotalDocsExamined? Add/fix the index (use ESR). 4. Check the sort and the projection. 5. Check document size and RAM. 6. Re-measure.
Security
Lock the database down and protect your API.
- Turn on authentication (SCRAM) and use role-based access control. Give each app only the role it needs (
readWriteon one database, notroot). - Use TLS for connections and encryption at rest. For very sensitive fields use Client-Side Field Level Encryption.
- Network: never expose port 27017 to the internet. Use firewall, private network/VPC, or the Atlas IP allow list.
- Keep credentials in environment variables, never in Git. Rotate them.
- Enable auditing and backups, and test restores.
- Keep MongoDB and drivers updated.
NoSQL injection
// Attacker sends JSON: { "email": "admin@x.com", "password": { "$ne": null } }
const user = await User.findOne({ email: req.body.email, password: req.body.password });
// The filter becomes: password is "not null" → matches → logged in!
Fixes
- Validate input types (
typeof password === "string") with zod/joi. - Use
express-mongo-sanitizeor MongoosesanitizeFilter. - Compare hashed passwords with
bcrypt.compare, never put the password in the query. - Do not use
$wherewith user input.
Interview focus
Many old MongoDB servers were hacked because they ran without auth on a public IP. Name those three basics: authentication, network restriction, and least-privilege roles.
Change Streams, Time Series, GridFS & Atlas
Powerful features beyond basic CRUD.
Change streams: react to data changes in real time
const stream = db.collection("orders").watch([{ $match: { operationType: "insert" } }]);
for await (const change of stream) {
console.log("New order:", change.fullDocument._id); // send an email, push a notification...
}
Needs a replica set or sharded cluster. Supports a resume token so you can continue after a restart. Better than polling.
Other special collections and features
| Feature | Use |
|---|---|
| Capped collection | Fixed size, keeps insertion order, oldest data is overwritten (logs) |
| TTL index | Expire documents after some time (sessions, OTP) |
| Time series collection | Optimised storage for measurements over time (IoT, metrics), since 5.0 |
| GridFS | Store files bigger than 16 MB in chunks (default 255 KB) |
Geospatial (2dsphere) |
$near, $geoWithin queries |
MongoDB Atlas
Atlas is MongoDB's managed cloud service: automated backups, scaling, monitoring, security, and extras:
- Atlas Search: full-text search (Lucene based).
- Atlas Vector Search: store embeddings and run similarity search with
$vectorSearch. Useful for AI apps and RAG (store chunks + embedding in the same document). - Tools: Compass (GUI), mongosh (shell),
mongodump/mongorestore(backup / restore),mongoexport/mongoimport(JSON/CSV).
// Vector search sketch (RAG)
db.chunks.aggregate([
{ $vectorSearch: { index: "vec_idx", path: "embedding", queryVector: qVec, numCandidates: 100, limit: 5 } },
{ $project: { text: 1, score: { $meta: "vectorSearchScore" } } }
]);
Interview focus
- "How do you get live updates without polling?" → change streams.
- "Store a 50 MB video?" → GridFS (or object storage like S3 and keep the URL in MongoDB).
MongoDB vs SQL
A fair comparison for interviews.
| Topic | MongoDB | SQL (PostgreSQL / MySQL) |
|---|---|---|
| Data model | Documents (JSON-like) | Tables and rows |
| Schema | Flexible (can add validation) | Fixed, strict |
| Relations | Embed or reference, $lookup |
Foreign keys, JOINs |
| Scaling | Built-in sharding | Mostly vertical, sharding is harder |
| Transactions | Single doc atomic, multi-doc supported | Strong and mature everywhere |
| Query language | MQL + aggregation pipeline | SQL |
| Best for | Changing schema, nested data, scale-out | Complex relations, reporting, strict integrity |
| Consistency | Tunable (read/write concern) | Strong by default |
ACID vs BASE: relational databases are classic ACID. "BASE" (Basically Available, Soft state, Eventual consistency) describes systems that relax consistency for availability. MongoDB lets you choose per operation using write and read concern.
Interview focus
A balanced answer wins: "I pick based on the data and access patterns. For a social feed or product catalog I like MongoDB. For a payments ledger with many relations I'd lean to PostgreSQL." Also mention that PostgreSQL has JSONB and MongoDB has transactions, so the gap is smaller than people think.
Common Mistakes & Cheat Sheet
Last-minute revision.
Mistakes to avoid
- Using
_idas a string in queries instead ofObjectId(raw driver). - Forgetting
{ new: true }/returnDocument: "after"andrunValidators: truein Mongoose updates. - Storing money as floats.
- No index on fields used in filters and sorts (hidden COLLSCAN).
- Unbounded arrays and huge documents.
- Using
skipfor deep pagination. - Exposing the database publicly without authentication.
- Passing
req.bodydirectly into a query (NoSQL injection). - Opening a new connection per request.
- Thinking
unique: truein a Mongoose schema validates (it creates an index only).
Numbers worth remembering
| Fact | Value |
|---|---|
| Max document size | 16 MB |
| Max nesting depth | 100 levels |
| ObjectId size | 12 bytes (4 time + 5 random + 3 counter) |
| Default port | 27017 |
| Replica set size | up to 50 members, 7 voting |
| Heartbeat / election timeout | 2 s / about 10 s |
| Default storage engine | WiredTiger |
| Checkpoint interval | about 60 s |
| Transaction time limit | 60 s |
| Default write concern | w: "majority" (5.0+) |
| Default read concern / preference | local / primary |
| Chunk size (default) | 128 MB |
| Default slow query threshold | 100 ms |
| TTL monitor | runs about every 60 s |
30-second answer: "Tell me about MongoDB"
MongoDB is a document database that stores BSON documents in collections. It has a flexible schema, rich queries and an aggregation pipeline, and indexes for speed. For availability it uses replica sets with automatic failover, and for scale it uses sharding. I model data around how the app reads it, embedding data that is read together and referencing data that grows. In MERN projects I use Mongoose, careful indexes, and I check queries with
explain.
index or shard.Done reading? Test yourself now. Active recall beats re-reading.
Go to Q&A practice →