Interviewers who ask about MongoDB in production rarely care whether you remember the syntax of find. They want to see that you understand what happens when a primary fails mid-write, why a query that was fast at ten thousand documents crawls at ten million, and how a poor shard key can make a cluster run at the speed of one machine.
This guide covers the decisions that separate someone who has used MongoDB from someone who has operated it: document modelling, index design, durability guarantees, replication and failover, sharding, transactions and aggregation performance. Each concept includes a short example from an invented system and the traps that show up in real incidents and in interview answers.
Study order
If time is short, go in this order.
- Schema design: embedding, referencing and bounded growth
Most MongoDB performance and consistency problems trace back to the document model, and interviewers usually start here.
- Compound indexes, the ESR rule and reading explain output
Index order and reading explain output are the most frequent practical topics and the fastest way to show real experience.
- Write concern and read concern: what acknowledged actually means
Knowing what acknowledgement guarantees, and when data can be rolled back, separates senior answers from mid-level ones.
- Replica sets, elections and surviving failover
Every production deployment is a replica set, and failover behaviour drives your client configuration and error handling.
- Read preference, stale secondaries and causal consistency
Secondary reads are a common scaling idea with subtle consistency bugs that interviewers like to probe.
- Multi-document transactions and when to avoid them
You need to explain both how to use transactions correctly and why good schemas rarely need them.
- Sharding and choosing a shard key
Sharding questions appear at senior level and hinge almost entirely on shard key reasoning.
- Aggregation pipeline performance
Pipeline ordering and memory limits come up in reporting and analytics scenarios.
Schema design: embedding, referencing and bounded growth
In MongoDB you model for your access patterns, not for normalisation. Data that is read together, changes together and has a bounded size belongs in the same document. Data that grows without limit, is shared between many parents, or is read on its own belongs in a separate collection and is linked by reference.
Take Tidewell, a parcel-locker company. An order has two to five line items that are always shown with the order, so they are embedded. Each locker also sends a temperature and door reading every 30 seconds, which is unbounded. Pushing those into the locker document would eventually hit the 16 MB document limit and make every update rewrite a larger and larger document. Instead you bucket readings: one document per locker per hour, capped at a fixed count, or you use a time series collection, which does this bucketing for you.
A strong answer names the trade-off. Embedding gives you single-document atomicity and one read per page. Referencing gives you independent growth and avoids duplication, but costs extra queries or a $lookup. Duplicating a few fields, such as a customer name on the order, is fine when you accept that the copy can go stale or you have a plan to update it.
JavaScript
// Bounded, read together: embed the line items
db.orders.insertOne({
_id: "ord_8812",
lockerId: "lk_204",
customerId: "cus_51",
status: "awaiting_pickup",
items: [
{ sku: "BAT-AA-8", qty: 2, priceCents: 799 },
{ sku: "CBL-USBC-1M", qty: 1, priceCents: 1299 }
],
createdAt: new Date()
});
// Unbounded: bucket sensor readings, max 200 per document
db.lockerReadings.updateOne(
{ lockerId: "lk_204", hour: ISODate("2024-05-03T14:00:00Z"), count: { $lt: 200 } },
{
$push: { readings: { t: new Date(), tempC: 21.4, doorOpen: false } },
$inc: { count: 1 }
},
{ upsert: true }
);When a bucket reaches 200 readings the filter stops matching and the upsert starts a new bucket for the same hour.
Traps
- Embedding an array that grows forever, such as comments or events, until documents approach 16 MB and every update gets slower.
- Copying a relational schema one table per collection and then rebuilding joins with
$lookupon every request. - Duplicating fields for read speed without deciding how and when the copies are updated.
- Forgetting that a unique index on the bucket key breaks the bucket-overflow upsert pattern shown above.
Compound indexes, the ESR rule and reading explain output
A compound index is useful for a query only through a prefix of its fields, and field order decides how much work the query does. The usual guideline is ESR: fields tested for equality first, then fields you sort on, then fields with range conditions. Equality fields narrow the scan to one contiguous slice, the sort fields let MongoDB walk that slice already in order, and the range field filters within it.
Suppose Quaymark, a support desk, lists open tickets for a team ordered by priority, created in the last seven days. With the index { teamId: 1, status: 1, priority: -1, createdAt: 1 } the query uses the index for both filtering and ordering, so there is no in-memory sort. If you put createdAt before priority, the range would break the ordering and MongoDB would need a blocking SORT stage.
Verify with explain("executionStats"). Compare nReturned with totalKeysExamined and totalDocsExamined: a healthy query examines roughly as many keys as it returns. Look for IXSCAN rather than COLLSCAN, and for the absence of a SORT stage. A covered query, where the projection only uses indexed fields and excludes _id, shows totalDocsExamined: 0.
JavaScript
db.tickets.createIndex({ teamId: 1, status: 1, priority: -1, createdAt: 1 });
const since = new Date(Date.now() - 7 * 24 * 3600 * 1000);
const plan = db.tickets
.find({ teamId: "payments", status: "open", createdAt: { $gte: since } })
.sort({ priority: -1 })
.limit(50)
.explain("executionStats");
printjson({
returned: plan.executionStats.nReturned,
keys: plan.executionStats.totalKeysExamined,
docs: plan.executionStats.totalDocsExamined
});Equality on teamId and status, sort on priority, range on createdAt, in that order.
Traps
- Putting the range field before the sort field and getting an in-memory sort that fails or spills on large results.
- Adding an index for every query: each index slows writes, takes RAM and must be maintained on every replica.
- Indexing low-selectivity fields alone, such as a boolean, and expecting it to help.
- Trusting a fast query on a small dev dataset instead of checking keys and documents examined.
- Building a large index on a busy primary without planning for the extra load and replication of the build.
Write concern and read concern: what acknowledged actually means
Write concern controls when the server acknowledges a write. w: 1 means the primary applied it. w: "majority" means a majority of voting members have it, which is the default for most replica set configurations since MongoDB 5.0. j: true additionally requires the write to be in the on-disk journal. Only majority-acknowledged writes are guaranteed to survive a failover; a w: 1 write that had not replicated can be rolled back when the old primary rejoins.
Read concern controls what data a read can see. local returns the latest data on the node, which may later be rolled back. majority returns only data acknowledged by a majority, so it never disappears. snapshot gives a consistent point-in-time view, mainly inside transactions. linearizable guarantees you see all majority writes completed before the read started, at a real latency cost, and only on the primary.
In an interview, tie the choice to the business consequence. For Ferrow, a payouts service, losing a recorded payout after a failover means paying twice, so payouts use majority writes and majority reads. A click-tracking counter can accept w: 1 because losing a few increments in a rare failover is acceptable.
JavaScript
db.payouts.insertOne(
{ _id: "po_30117", merchantId: "m_88", amountCents: 452000, status: "sent" },
{ writeConcern: { w: "majority", j: true, wtimeout: 5000 } }
);
const sent = db.payouts
.find({ merchantId: "m_88", status: "sent" })
.readConcern("majority")
.toArray();Majority write plus majority read: what Ferrow reads cannot be rolled back.
Traps
- Assuming a
wtimeouterror means the write failed. It only means acknowledgement did not arrive in time; the write may still be applied and replicate later. - Using
w: 1for financial or inventory data and being surprised by rollbacks after a failover. - Writing with majority but reading with
localfrom a secondary and expecting to see your own write. - Adding an arbiter to a primary-secondary-arbiter set and not realising majority writes stall when the secondary is down.
Replica sets, elections and surviving failover
A replica set has one primary that accepts writes and secondaries that replicate its oplog. If the primary becomes unreachable, the remaining members hold an election, and a new primary needs votes from a majority of voting members. With the default electionTimeoutMillis of 10 seconds, the cluster is typically writable again within seconds, but your application sees errors during that window.
Odd member counts matter because of majority arithmetic. Three members tolerate one failure; four members still tolerate only one. Placement matters too: with two members in one data centre and one in another, losing the first data centre leaves no majority, so you need a third location for automatic failover across sites.
On the application side, modern drivers enable retryable writes and retryable reads by default. A single-document write that hits a network error or a NotWritablePrimary error is retried once against the new primary, and the server uses a transaction number to avoid applying it twice. You still need sensible timeouts, such as serverSelectionTimeoutMS, so requests fail fast instead of piling up while no primary exists.
JavaScript
const { MongoClient } = require("mongodb");
const client = new MongoClient(
"mongodb://db1.tidewell.internal,db2.tidewell.internal,db3.tidewell.internal/?replicaSet=rs0",
{
retryWrites: true,
retryReads: true,
w: "majority",
serverSelectionTimeoutMS: 15000,
maxPoolSize: 50
}
);
async function main() {
await client.connect();
const lockers = client.db("tidewell").collection("lockers");
await lockers.updateOne({ _id: "lk_204" }, { $set: { online: true } });
await client.close();
}
main().catch(console.error);List every seed member and the replica set name so the driver can discover the new primary on its own.
Traps
- Assuming retryable writes cover everything: multi-document writes such as
updateManyanddeleteManyare not retryable. - Deploying an even number of voting members, or all members in one availability zone.
- Connecting to a single host instead of the replica set, so the app cannot follow the primary after an election.
- Never testing failover with
rs.stepDown()before production forces the test on you.
Read preference, stale secondaries and causal consistency
Read preference decides which members serve reads: primary (the default), primaryPreferred, secondary, secondaryPreferred or nearest. Reading from secondaries spreads load and reduces latency for distant clients, but secondaries replicate asynchronously, so they can lag behind the primary by milliseconds or, under heavy load, by minutes.
The usual production rule is to read from the primary for anything a user just changed and to send analytics, exports and reports to secondaries. maxStalenessSeconds, which must be at least 90, excludes secondaries that lag too far. A dedicated hidden member or an analytics-tagged member is a cleaner way to keep heavy reporting away from nodes that might become primary.
If you must read your own writes from secondaries, use a causally consistent session with majority read and write concern. The driver then passes the operation time of your write, and the secondary waits until it has caught up to that point before answering. Without a session, a user who updates a delivery address and immediately reloads the page from a lagging secondary sees the old address.
JavaScript
const session = client.startSession({ causalConsistency: true });
const customers = client.db("tidewell").collection("customers");
try {
await customers.updateOne(
{ _id: "cus_51" },
{ $set: { address: "14 Harbour Row" } },
{ session, writeConcern: { w: "majority" } }
);
const fresh = await customers.findOne(
{ _id: "cus_51" },
{ session, readPreference: "secondaryPreferred", readConcern: { level: "majority" } }
);
console.log(fresh.address);
} finally {
await session.endSession();
}The secondary waits until it has applied the update before serving the read.
Traps
- Using
secondaryPreferredglobally to scale reads and introducing read-your-own-write bugs. - Treating secondaries as extra capacity: if a secondary fails over to primary, the reporting load lands on the primary too.
- Expecting causal consistency to hold across different sessions or with
w: 1writes.
Multi-document transactions and when to avoid them
A single-document write is always atomic, which is why good schema design removes most of the need for transactions. When a change genuinely spans documents, MongoDB supports ACID transactions on replica sets since 4.0 and on sharded clusters since 4.2. Inside a transaction, reads see a snapshot and writes become visible to others only at commit.
Transactions have costs. By default a transaction that runs longer than 60 seconds is aborted. Two transactions touching the same document produce a write conflict, and one of them fails with a TransientTransactionError. A commit can also return UnknownTransactionCommitResult when the outcome is uncertain. The driver's withTransaction helper retries both cases, so your callback must be safe to run more than once.
For Quaymark's event ticketing, holding a seat and creating the pending order must succeed or fail together. The seat update uses a conditional filter, heldBy: null, so two buyers cannot take the same seat; the transaction makes sure an order is never created without its seat.
JavaScript
async function holdSeat(client, orderId) {
const db = client.db("quaymark");
const session = client.startSession();
try {
await session.withTransaction(async () => {
const res = await db.collection("seats").updateOne(
{ eventId: "ev_77", seat: "C14", heldBy: null },
{ $set: { heldBy: orderId } },
{ session }
);
if (res.modifiedCount !== 1) throw new Error("Seat C14 is no longer available");
await db.collection("orders").insertOne(
{ _id: orderId, eventId: "ev_77", seats: ["C14"], status: "pending" },
{ session }
);
}, { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } });
} finally {
await session.endSession();
}
}Throwing inside the callback aborts the transaction and the error reaches the caller.
Traps
- Forgetting to pass
sessionto an operation, which silently runs it outside the transaction. - Doing slow work such as HTTP calls or emails inside the callback, which can run several times on retry.
- Using transactions to patch a schema that should have kept related data in one document.
- Running large batch updates in one transaction and hitting the time limit or cache pressure.
Aggregation pipeline performance
The aggregation pipeline processes documents stage by stage, and order determines cost. A $match at the start can use an index; the same filter after a $group or $unwind scans everything. A $sort at the start can also use an index, and a $sort followed by $limit is coalesced into a top-k sort that keeps only the needed documents in memory.
Each blocking stage such as $group or $sort has a 100 MB memory limit. Beyond that, the stage must spill to disk, which is allowed when allowDiskUse is true (the default from MongoDB 6.0), or the query fails. Spilling works but is slow, so the real fix is usually filtering earlier or pre-aggregating.
$lookup runs a query against the foreign collection for incoming documents, so the foreign field needs an index, and a $lookup placed before a $match multiplies that work. For dashboards queried constantly, consider materialising results with $merge on a schedule instead of recomputing them on every page load.
JavaScript
db.rides.aggregate(
[
{ $match: {
cityId: "lis",
endedAt: { $gte: ISODate("2024-05-01"), $lt: ISODate("2024-06-01") }
} },
{ $project: { riderId: 1, fareCents: 1 } },
{ $group: { _id: "$riderId", rides: { $sum: 1 }, spentCents: { $sum: "$fareCents" } } },
{ $sort: { spentCents: -1 } },
{ $limit: 20 }
],
{ allowDiskUse: true }
);Top 20 riders in Lisbon for May: filter with an index first, group second, top-k sort last.
Traps
- Putting
$matchafter$unwindor$groupso it cannot use an index. - Running
$lookupagainst an unindexed foreign field. - Treating
allowDiskUseas a fix rather than a sign the pipeline processes too much data. - Running heavy analytics pipelines on the primary during peak traffic instead of on a secondary or analytics node.
Common questions
Short answers to the usual doubts.
Do I need transactions to keep MongoDB data consistent?
Usually not. Writes to a single document are atomic, so a schema that keeps data changed together in one document needs no transaction. Use transactions when an invariant truly spans documents or collections, keep them short, and let withTransaction handle retries.
Is w: "majority" slower than w: 1, and is it worth it?
It adds the latency of replication to at least one secondary, typically a few milliseconds within one region and more across regions. In return, acknowledged writes survive failover. For data you cannot afford to lose, that trade is almost always worth it, and it is the default on most modern replica sets.
When should I shard instead of scaling up a replica set?
Shard when the working set or write throughput no longer fits a single primary even after index tuning and vertical scaling, or when data size makes backups and resyncs impractical. Sharding adds operational complexity and makes the shard key a long-term commitment, so do not shard by default.
How do I tell whether a slow query needs a new index?
Run it with explain("executionStats"). A COLLSCAN, a large gap between keys or documents examined and documents returned, or an in-memory SORT stage all point to a missing or badly ordered index. The database profiler and slow query log help you find which queries to examine first.
Can I read from secondaries to scale reads safely?
Only for reads that tolerate stale data, such as reports or exports. For user-facing reads after a write, read from the primary or use causally consistent sessions with majority concerns. Remember that secondaries also do the same write work as the primary, so they are not free capacity.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- MongoDB in productionTake the test
- Model an online shop in MongoDBSolve the exercise