MongoDB and Amazon DocumentDB - Interview Preparation (2026 Edition)
Total Questions: 65 Curriculum: Core Fundamentals (100), Intermediate (120), Advanced (80)
Core Fundamentals
Q1: What is MongoDB and how is it different from SQL databases?
Technical Answer: MongoDB is a NoSQL document database that stores data as JSON-like documents. Unlike SQL databases with fixed schemas and tables, MongoDB has dynamic schemas, horizontal scaling, and rich query capabilities for nested data.
Key Differences:
| Aspect | MongoDB | SQL Database |
|---|---|---|
| Data Model | Documents (BSON) | Rows in Tables |
| Schema | Dynamic/Flexible | Fixed/Rigid |
| Joins | Manual with $lookup | Native foreign keys |
| Scaling | Horizontal sharding | Vertical + limited horizontal |
| Transactions | Multi-document (4.0+) | ACID across tables |
Basic Operations:
// Insert documents
db.users.insertMany([
{ name: "Alice", age: 30, tags: ["admin", "user"] },
{ name: "Bob", age: 25, tags: ["user"] },
]);
// Query with nested conditions
db.users.find({
age: { $gte: 25, $lte: 35 },
tags: "admin",
});
// Update syntax
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 31 }, $push: { tags: "premium" } },
);
🔍 Interviewer Notes: Testing document model understanding and use case selection.
❌ Common Mistakes:
- Treating documents like tables with joins
- Not considering document growth
- Ignoring indexing on query fields
Q2: What are the core MongoDB operations and query operators?
Technical Answer: MongoDB provides CRUD operations with rich query operators. Understanding projection, sorting, and cursor operations is essential for efficient queries.
CRUD Operations:
// CREATE - insertOne, insertMany
db.products.insertOne({
name: "Laptop",
price: 999,
specs: { cpu: "i7", ram: "16GB" },
});
// READ - find with projection
db.products
.find(
{ price: { $gt: 500 } }, // filter
{ name: 1, price: 1 }, // projection (include only)
)
.sort({ price: -1 })
.limit(10);
// UPDATE - updateOne, updateMany, findAndModify
db.products.updateMany(
{ category: "electronics" },
{ $mul: { price: 0.9 } }, // 10% discount
);
// DELETE - deleteOne, deleteMany
db.products.deleteMany({ price: { $lt: 10 } });
Query Operators:
// Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
db.users.find({ age: { $in: [25, 30, 35] } });
// Logical: $and, $or, $not, $nor
db.users.find({
$or: [
{ status: "active", lastLogin: { $gte: new Date(Date.now() - 86400000) } },
{ role: "admin" },
],
});
// Element: $exists, $type
db.users.find({ phone: { $exists: true, $type: "string" } });
// Evaluation: $regex, $text, $expr
db.users.find({ name: { $regex: /^A/, $options: "i" } });
🔍 Interviewer Notes: Testing query construction and operator knowledge.
❌ Common Mistakes:
- Not using projection to limit data transfer
- Regex queries without indexes
- Case-sensitive string comparisons
Q3: How does MongoDB indexing work and what types are available?
Technical Answer: MongoDB uses B-tree indexes for efficient queries. Single field, compound, multikey (array), text, geospatial, and hashed indexes support different query patterns. Index selection affects query performance significantly.
Index Types and Creation:
// Single field index
db.users.createIndex({ email: 1 }); // ascending
db.users.createIndex({ createdAt: -1 }); // descending
// Compound index (order matters!)
db.orders.createIndex({ customerId: 1, orderDate: -1, status: 1 });
// Supports queries on: customerId, customerId+orderDate, all three fields
// Multikey index (for arrays)
db.products.createIndex({ tags: 1 }); // Automatically multikey
db.users.createIndex({ "addresses.city": 1 }); // Nested array field
// Text index
db.articles.createIndex({ title: "text", content: "text" });
// Query: db.articles.find({ $text: { $search: "mongodb database" } })
// Geospatial index
db.places.createIndex({ location: "2dsphere" });
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.9667, 40.78] },
$maxDistance: 5000,
},
},
});
// Hashed index (for sharding)
db.users.createIndex({ userId: "hashed" });
Index Analysis:
// Check query execution plan
db.users.find({ email: "alice@example.com" }).explain("executionStats");
// Show all indexes
db.users.getIndexes();
// Index size and usage stats
db.users.aggregate([{ $indexStats: {} }]);
🔍 Interviewer Notes: Testing index strategy and performance optimization.
❌ Common Mistakes:
- Too many indexes slowing writes
- Wrong field order in compound indexes
- Not using covered queries (all fields in index)
Q4: What is aggregation pipeline and how to use it?
Technical Answer: The aggregation pipeline processes documents through stages, transforming and computing results. Each stage transforms the stream, enabling complex data processing like grouping, filtering, and computing statistics.
Common Pipeline Stages:
// Match and group
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 },
avgOrder: { $avg: "$amount" },
},
},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 },
]);
// Lookup (join equivalent)
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo",
},
},
{ $unwind: "$customerInfo" },
{
$project: {
orderId: "$_id",
customerName: "$customerInfo.name",
amount: 1,
},
},
]);
// Group with multiple operations
db.sales.aggregate([
{
$group: {
_id: { $dateToString: { format: "%Y-%m", date: "$date" } },
totalRevenue: { $sum: "$amount" },
uniqueCustomers: { $addToSet: "$customerId" },
orders: { $push: "$$ROOT" },
},
},
{ $addFields: { customerCount: { $size: "$uniqueCustomers" } } },
]);
// Faceted search
db.products.aggregate([
{
$facet: {
priceRanges: [
{
$bucket: {
groupBy: "$price",
boundaries: [0, 50, 100, 200, 500],
output: { count: { $sum: 1 } },
},
},
],
categories: [
{ $group: { _id: "$category", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
],
},
},
]);
🔍 Interviewer Notes: Testing data transformation and analytics capabilities.
❌ Common Mistakes:
- Not using
$matchearly to reduce pipeline size - Missing
$projectfor field selection - Performance issues with large
$lookupoperations
Q5: What is Amazon DocumentDB and how does it compare to MongoDB?
Technical Answer: Amazon DocumentDB is a MongoDB-compatible document database service. It uses MongoDB 4.0 wire protocol but has differences in features, performance, and management. It provides managed scaling but with some feature trade-offs.
Key Comparisons:
| Feature | DocumentDB | MongoDB Atlas |
|---|---|---|
| Protocol | MongoDB 4.0 | MongoDB 7.0+ |
| ACID Transactions | Single document | Multi-document (4.0+) |
| Aggregation | Limited operators | Full pipeline |
| Sharding | Manual setup | Automated |
| Backup | Automated snapshots | Continuous/cloud backup |
| Scaling | Vertical + read replicas | Horizontal + global clusters |
Connection Example:
from pymongo import MongoClient
# DocumentDB connection (note SSL requirement)
client = MongoClient(
'cluster-endpoint.docdb.amazonaws.com:27017',
username='admin',
password='password',
ssl=True,
ssl_ca_certs='rds-combined-ca-bundle.pem',
replicaSet='rs0'
)
db = client['mydatabase']
collection = db['users']
# Same query syntax as MongoDB
users = collection.find({"age": {"$gte": 25}})
Limitations to Know:
// DocumentDB limitations
// 1. No $graphLookup aggregation stage
db.users.aggregate([
{
$graphLookup: {
from: "users",
startWith: "$managerId",
connectFromField: "managerId",
connectToField: "_id",
as: "reports",
},
},
]); // NOT SUPPORTED
// 2. Limited text search
db.articles.createIndex({ content: "text" });
db.articles.find({ $text: { $search: "database" } }); // Limited features
// 3. No change streams (until recent versions)
db.users.watch(); // Check version compatibility
🔍 Interviewer Notes: Testing managed service differences and migration considerations.
❌ Common Mistakes:
- Assuming full MongoDB feature parity
- Not testing aggregation pipeline compatibility
- Missing DocumentDB-specific connection requirements
Q6: How to handle MongoDB transactions and data consistency?
Technical Answer: MongoDB supports multi-document ACID transactions (4.0+). They use snapshot isolation and require careful consideration for performance. Write concern and read concern settings control consistency levels.
Transaction Example:
// Single document operation (no transaction needed)
db.accounts.updateOne(
{ _id: accountId, balance: { $gte: amount } },
{ $inc: { balance: -amount } },
);
// Multi-document transaction
session = db.getMongo().startSession();
session.startTransaction({
readConcern: { level: "snapshot" },
writeConcern: { w: "majority" },
});
try {
db.accounts.updateOne(
{ _id: fromAccount },
{ $inc: { balance: -amount } },
{ session },
);
db.accounts.updateOne(
{ _id: toAccount },
{ $inc: { balance: amount } },
{ session },
);
db.transactions.insertOne(
{
from: fromAccount,
to: toAccount,
amount: amount,
timestamp: new Date(),
},
{ session },
);
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
await session.endSession();
}
Consistency Levels:
// Write concerns
db.products.insertOne(
{ name: "Item" },
{ writeConcern: { w: "majority", j: true } }, // Acknowledged by majority + journal
);
// Read concerns
db.products.find().readConcern("majority"); // Most recent majority-committed data
db.products.find().readConcern("local"); // Locally committed (default)
🔍 Interviewer Notes: Testing distributed transaction understanding.
❌ Common Mistakes:
- Wrapping single operations in transactions (performance overhead)
- Long-running transactions causing locks
- Not handling transaction timeouts
Q7: How to model relationships in MongoDB?
Technical Answer: MongoDB uses embedding for one-to-few relationships and referencing for one-to-many or one-to-squillions. The choice affects query patterns, data consistency, and document growth.
Relationship Patterns:
// 1. Embedding (One-to-Few)
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
addresses: [
// Embedded sub-documents
{ type: "home", street: "123 Main St", city: "NYC" },
{ type: "work", street: "456 Park Ave", city: "NYC" },
],
});
// 2. Referencing (One-to-Many)
db.users.insertOne({
name: "Bob",
email: "bob@example.com",
});
db.posts.insertMany([
{ userId: ObjectId("..."), title: "Post 1", content: "..." },
{ userId: ObjectId("..."), title: "Post 2", content: "..." },
]);
// 3. Parent References (One-to-Squillions)
db.comments.insertOne({
postId: ObjectId("post-id"),
userId: ObjectId("user-id"),
text: "Great post!",
timestamp: new Date(),
});
// 4. Denormalization with periodic updates
db.users.updateOne(
{ _id: userId },
{
$set: {
postCount: db.posts.countDocuments({ userId: userId }),
lastPostDate: db.posts.findOne({ userId: userId }, { sort: { date: -1 } })
?.date,
},
},
);
Schema Design Considerations:
// Avoid unbounded document growth
// BAD: Continuously pushing to array
db.users.updateOne({ _id: userId }, { $push: { allActivity: activity } });
// BETTER: Separate collection for activity
db.userActivity.insertOne({ userId, activity, timestamp });
// GOOD: Bucket pattern for time-series
db.userActivity.insertOne({
userId,
date: ISODate("2024-01-15"),
activities: [
{ time: "09:00", action: "login" },
{ time: "09:30", action: "purchase" },
],
});
🔍 Interviewer Notes: Testing schema design skills for document databases.
❌ Common Mistakes:
- Over-embedding causing document size issues
- Missing indexes on reference fields
- Not planning for data growth patterns
Q8: What are MongoDB performance optimization techniques?
Technical Answer: MongoDB performance optimization involves proper indexing, query optimization, schema design, and hardware considerations. Understanding explain plans and profiling is crucial for identifying bottlenecks.
Performance Tools:
// Explain plan analysis
db.orders
.find({ customerId: "123", status: "shipped" })
.explain("executionStats");
// Profile slow queries
db.setProfilingLevel(1, { slowms: 100 }); // Log queries > 100ms
db.system.profile.find().sort({ ts: -1 }).limit(5);
// Current operations
db.currentOp();
// Performance recommendations from explain
// - COLLSCAN means missing index
// - Large docs examined indicates inefficient query
Optimization Strategies:
// 1. Covered queries (index-only)
db.users.createIndex({ email: 1, name: 1 });
db.users.find(
{ email: "alice@example.com" },
{ _id: 0, email: 1, name: 1 }, // Only indexed fields
);
// 2. Pagination with _id for large datasets
db.posts
.find({
_id: { $gt: lastSeenId },
status: "published",
})
.sort({ _id: 1 })
.limit(20);
// 3. Update optimization
// USE: Targeted update
db.users.updateOne(
{ _id: userId, lastLogin: { $lt: cutoffDate } },
{ $set: { status: "inactive" } },
);
// AVOID: Unqualified update (affects all docs!)
db.users.updateMany({}, { $set: { status: "inactive" } });
// 4. Aggregation optimization with $facet
// USE: Parallel execution of multiple pipelines
db.collection.aggregate([
{
$facet: {
group1: [
/* pipeline 1 */
],
group2: [
/* pipeline 2 */
],
},
},
]);
🔍 Interviewer Notes: Testing performance troubleshooting skills.
❌ Common Mistakes:
- Not analyzing query execution plans
- Missing compound indexes for multi-field queries
- Using skip() on large collections
Q9: How to implement MongoDB security best practices?
Technical Answer: MongoDB security involves authentication, authorization, encryption, network security, and auditing. Enabling TLS, proper user roles, field-level encryption, and network isolation are essential.
Security Configuration:
// 1. User roles and permissions
db.createUser({
user: "appUser",
pwd: "securePassword",
roles: [
{ role: "readWrite", db: "myapp" },
{ role: "changeStreamAnyResource", db: "admin" }
]
})
// 2. Field-level encryption (Client-side)
const { ClientEncryption } = require('mongodb-client-encryption')
const encryptedFields = {
fields: [
{
path: "ssn",
bsonType: "string",
queries: [{ queryType: "equality" }]
}
]
}
// 3. Network security
// mongod.conf
net:
bindIp: 127.0.0.1 # Bind to localhost only
port: 27017
security:
authorization: enabled
javascriptEnabled: false # Disable server-side JS
// 4. IP whitelisting (Atlas/DocumentDB)
// Configure VPC security groups or IP access lists
Audit Logging:
// Enable audit log
auditLog:
destination: file
path: /var/log/mongodb/audit.log
format: JSON
// Audit specific operations
db.setLogLevel(2, "audit")
🔍 Interviewer Notes: Testing security implementation knowledge.
❌ Common Mistakes:
- Leaving default configuration in production
- Over-privileged database users
- Not encrypting data at rest/transit
Q10: How to backup and restore MongoDB?
Technical Answer: MongoDB backup strategies include logical backups (mongodump), filesystem snapshots, and cloud-native solutions. Point-in-time recovery requires oplog tailing. Restore strategies depend on backup type and recovery time objectives.
Backup Methods:
# 1. Logical backup with mongodump
mongodump --host localhost:27017 --db myapp --out /backup/2024-01-15/
mongodump --host cluster0-shard-00-00.xyz.mongodb.net --username admin --password pass --authenticationDatabase admin
# Selective backup with query
mongodump --db myapp --collection orders --query '{"status": "completed"}' --out /backup/completed-orders/
# 2. Filesystem snapshot (mongod stopped or locked)
# AWS EBS snapshot or LVM snapshot
db.fsyncLock() # Lock writes
# Take filesystem snapshot
db.fsyncUnlock() # Unlock writes
# 3. MongoDB Atlas continuous backup
# Enabled in Atlas UI or via API
Restore Methods:
# From mongodump
mongorestore --host localhost:27017 --db myapp /backup/2024-01-15/
# Point-in-time recovery using oplog
mongodump --host localhost:27017 --oplog
mongorestore --host localhost:27017 --oplogReplay --oplogLimit 1640995200:1
# Selective restore
mongorestore --db myapp --collection users --drop /backup/2024-01-15/
DocumentDB Backup:
# DocumentDB uses snapshots
aws docdb create-db-cluster-snapshot \
--db-cluster-identifier my-cluster \
--db-cluster-snapshot-identifier my-snapshot
# Restore from snapshot
aws docdb restore-db-cluster-from-snapshot \
--db-cluster-identifier new-cluster \
--snapshot-identifier my-snapshot
🔍 Interviewer Notes: Testing disaster recovery planning and implementation.
❌ Common Mistakes:
- Not testing restore procedures regularly
- Missing backup verification
- Backups stored in same region without offsite copies
Q11: How do you implement MongoDB transactions across multiple documents?
Technical Answer: MongoDB supports multi-document ACID transactions starting in version 4.0. Transactions use sessions and provide snapshot isolation. They require replica sets or sharded clusters and have performance implications.
Transaction Implementation:
const session = client.startSession();
try {
await session.withTransaction(
async () => {
// All operations in transaction
const transferAmount = 100;
// Debit from account A
await accountsCollection.updateOne(
{ _id: accountIdA, balance: { $gte: transferAmount } },
{ $inc: { balance: -transferAmount } },
{ session },
);
// Credit to account B
await accountsCollection.updateOne(
{ _id: accountIdB },
{ $inc: { balance: transferAmount } },
{ session },
);
// Log transaction
await transactionsCollection.insertOne(
{
from: accountIdA,
to: accountIdB,
amount: transferAmount,
timestamp: new Date(),
},
{ session },
);
},
{
readConcern: { level: "snapshot" },
writeConcern: { w: "majority" },
},
);
} finally {
await session.endSession();
}
Retry Logic:
async function runTransactionWithRetry(txnFn, maxAttempts = 3) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await txnFn();
} catch (error) {
if (
error.hasErrorLabel("TransientTransactionError") &&
attempt < maxAttempts
) {
console.log(`Retrying transaction, attempt ${attempt}`);
continue;
}
throw error;
}
}
}
🔍 Interviewer Notes: Testing transaction boundaries and recovery patterns.
❌ Common Mistakes:
- Not handling transient transaction errors
- Too many documents in single transaction
- Not setting proper read/write concerns
Q12: What are aggregation pipeline optimization techniques?
Technical Answer: Aggregation optimization involves pipeline stage ordering, index usage, $match early filtering, $project for field selection, and avoiding unnecessary operations. Explain plans show actual execution strategy.
Optimization Patterns:
// ❌ Inefficient - matches late, projects late
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer",
},
},
{ $unwind: "$customer" },
{ $addFields: { total: { $sum: "$items.price" } } },
{ $match: { status: "completed" } }, // Filter applied too late
]);
// ✅ Efficient - match and project early
db.orders.aggregate([
{ $match: { status: "completed" } }, // Filter first
{ $project: { customerId: 1, items: 1 } }, // Project needed fields
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer",
},
},
{ $unwind: "$customer" },
{ $addFields: { total: { $sum: "$items.price" } } },
]);
// Using $facet for parallel processing
db.products.aggregate([
{
$facet: {
inStock: [
{ $match: { stock: { $gt: 0 } } },
{ $sort: { price: 1 } },
{ $limit: 10 },
],
lowStock: [{ $match: { stock: { $lt: 10 } } }],
},
},
]);
Index for Aggregation:
// Create index supporting $match and $sort
db.orders.createIndex({ status: 1, orderDate: -1 });
// Covered query aggregation
db.orders.aggregate([
{ $match: { status: "pending" } },
{ $project: { _id: 0, orderId: "$_id", total: 1 } }, // Only indexed fields
]);
🔍 Interviewer Notes: Testing query optimization expertise.
❌ Common Mistakes:
- Not using $match early in pipeline
- Missing indexes for $sort/$skip
- Not using covered queries
Q13: How do you handle MongoDB schema validation?
Technical Answer: MongoDB supports JSON Schema validation starting in version 3.2. Define validation rules on collections to enforce document structure, data types, and value constraints. Validation applies to inserts and updates.
Validation Examples:
// Collection with schema validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "createdAt", "status"],
properties: {
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
},
age: {
bsonType: "int",
minimum: 0,
maximum: 150,
},
status: {
enum: ["active", "inactive", "pending"],
description: "Must be one of the enum values",
},
createdAt: {
bsonType: "date",
},
tags: {
bsonType: "array",
items: { bsonType: "string" },
},
},
},
},
validationLevel: "strict", // strict|moderate|off
validationAction: "error", // error|warn
});
// Complex validation with expressions
db.createCollection("orders", {
validator: {
$expr: {
$and: [
{ $gte: ["$total", 0] },
{
$cond: [
{ $eq: ["$status", "completed"] },
{ $gt: ["$total", 10] },
true,
],
},
],
},
},
});
Update Validation Testing:
// Insert valid document
db.users.insertOne({
email: "user@example.com",
age: 25,
status: "active",
createdAt: new Date(),
});
// Insert invalid document - fails validation
try {
db.users.insertOne({
email: "invalid-email",
age: 200, // Exceeds maximum
status: "unknown", // Not in enum
});
} catch (e) {
console.log("Validation failed:", e.message);
}
🔍 Interviewer Notes: Testing data quality and constraint enforcement.
❌ Common Mistakes:
- Not versioning validation rules
- Too strict validation breaking existing data
- Not considering performance impact
Q14: How do you implement MongoDB change streams?
Technical Answer: Change streams provide real-time notifications of data changes using the oplog. They support all operations (insert, update, delete) and can filter by operation type or field values. Resume tokens enable fault-tolerant processing.
Change Stream Implementation:
// Basic change stream
const collection = db.collection("orders");
const changeStream = collection.watch([
{ $match: { operationType: { $in: ["insert", "update"] } } },
]);
changeStream.on("change", (change) => {
console.log("Change detected:", change.operationType);
if (change.operationType === "insert") {
// Process new order
sendNotification(change.fullDocument);
} else if (change.operationType === "update") {
// Process order update
updateInventory(change.updateDescription.updatedFields);
}
});
// Filtered change stream
const pipeline = [
{
$match: {
$or: [
{
operationType: "update",
"updateDescription.updatedFields.status": "shipped",
},
{ operationType: "insert", "fullDocument.priority": "high" },
],
},
},
];
const highPriorityStream = collection.watch(pipeline);
// Resume from last position
const lastToken = getLastProcessedToken();
const resumedStream = collection.watch(pipeline, { resumeAfter: lastToken });
Node.js Implementation:
const { MongoClient } = require("mongodb");
async function startChangeStream() {
const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("myapp");
const collection = db.collection("users");
const changeStream = collection.watch([], { fullDocument: "updateLookup" });
changeStream.on("change", async (change) => {
try {
await processChange(change);
saveResumeToken(change._id);
} catch (error) {
console.error("Change processing failed:", error);
// Don't advance past failed token
}
});
changeStream.on("error", (error) => {
console.error("Change stream error:", error);
// Reconnect logic
setTimeout(startChangeStream, 1000);
});
}
🔍 Interviewer Notes: Testing real-time data processing patterns.
❌ Common Mistakes:
- Not handling resume token persistence
- Missing error handling and reconnection
- Not filtering operations (performance impact)
Q15: How do you tune MongoDB performance for production?
Technical Answer: MongoDB performance tuning involves connection pooling, indexing strategy, query optimization, memory sizing, and hardware considerations. WiredTiger cache should be 50-60% of available RAM.
Connection Pool Optimization:
// Node.js connection pool
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017", {
maxPoolSize: 100, // Max connections
minPoolSize: 10, // Min connections
maxIdleTimeMS: 30000, // Close idle connections
waitQueueTimeoutMS: 2000, // Wait time for connection
socketTimeoutMS: 45000, // Socket timeout
});
// Connection monitoring
setInterval(() => {
const pool = client.topology.s.pool;
console.log({
available: pool.availableConnections.length,
inUse: pool.inUseConnections.length,
total: pool.totalConnections,
});
}, 30000);
Index Strategy:
// Compound index for common query patterns
db.orders.createIndex({
customerId: 1,
orderDate: -1,
status: 1,
});
// Partial index for specific subset
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { status: "active" } },
);
// TTL index for automatic cleanup
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 }, // 24 hours
);
Query Optimization:
// Ensure index coverage
db.products
.find(
{ category: "electronics", price: { $lt: 500 } },
{ name: 1, price: 1, _id: 0 }, // Only indexed fields
)
.sort({ price: 1 })
.explain("executionStats");
// Avoid skip for large offsets
// ❌ Bad
db.products.find().sort({ _id: 1 }).skip(10000).limit(10);
// ✅ Good - range query
const lastId = getLastSeenId();
db.products.find({ _id: { $gt: lastId } }).limit(10);
🔍 Interviewer Notes: Testing operational performance tuning.
❌ Common Mistakes:
- Too many open connections
- Missing indexes for sort operations
- Not monitoring slow queries
Q16: What is a compound index and how do you design one?
Technical Answer:
A compound index covers queries filtering/sorting on multiple fields (e.g., { tenant_id: 1, created_at: -1 }). Design by: equality fields first (most selective left), then sort fields, then range fields last. ESRI (Equality, Sort, Range) rule. Indexes support prefix subsets — {a, b} index also helps {a} queries, but not {b} alone.
Code/Syntax Justification:
db.orders.createIndex({ tenant_id: 1, created_at: -1 })
// Queries helped:
db.orders.find({ tenant_id: "t1" }).sort({ created_at: -1 })
// Not helped (leading field missing):
db.orders.find({ created_at: { $gt: ISODate(...) } })
🔍 Behind the Question: Index design theory and query patterns. ❌ The Red Flags: Random indexes on every field; no tenant_id-first pattern.
Q17: How does MongoDB sharding work and when do you enable it?
Technical Answer: Sharding horizontally partitions data across shards (each a replica set) by a shard key. The mongos router routes queries; the config server tracks chunk metadata. Enable when a single replica set exceeds capacity (data size, write throughput) or ops need. Shard key choice is critical — must have high cardinality, not monotonically increasing (hotspot risk), and match query patterns.
Code/Syntax Justification:
sh.enableSharding("saas")
sh.shardCollection("saas.orders", { tenant_id: 1, order_id: 1 })
// Hashed shard key avoids hotspots for high-write collections
sh.shardCollection("saas.events", { _id: "hashed" })
🔍 Behind the Question: Horizontal scaling decisions and key design.
❌ The Red Flags: Sharding on _id alone for tenant queries; poor key cardinality.
Q18: What is the difference between $lookup and denormalization?
Technical Answer:
$lookup performs left outer join across collections at query time — flexible but can be slow (no index across collections unless on the foreign field). Denormalization embeds related data (e.g., user name in order) for read speed — fast reads, but duplication and update complexity. Rule: embed for frequent reads of small related data; $lookup (or separate queries) for rarely-needed, large, or frequently-updated relations.
Code/Syntax Justification:
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user" } },
{ $unwind: "$user" }
])
🔍 Behind the Question: Data modeling trade-offs (embed vs reference).
❌ The Red Flags: $lookup in hot paths without indexes; embedding unbounded arrays.
Q19: What is an index vs a TTL index?
Technical Answer:
A TTL index (special index on a date field with expireAfterSeconds) lets MongoDB automatically delete documents after a timeout — ideal for sessions, logs, OTPs, and cache-like data. It runs a background job every 60s, so deletion isn't exact. Without it, you must write scheduled cleanup jobs.
Code/Syntax Justification:
db.sessions.createIndex({ last_activity: 1 }, { expireAfterSeconds: 3600 })
// Docs with last_activity older than 1h are auto-deleted
🔍 Behind the Question: Automatic data lifecycle management. ❌ The Red Flags: Manual cleanup loops when TTL exists; TTL on wrong field.
Q20: How do you handle MongoDB connection pooling at scale?
Technical Answer:
The driver maintains a connection pool per process. Tune maxPoolSize (default 100) to match concurrency — too low causes queueing, too high exhausts mongod connections. Use connection string options (maxPoolSize, minPoolSize, serverSelectionTimeoutMS). Never create a new MongoClient per request (leaks connections). In serverless, share clients across invocations and consider warm pools.
Code/Syntax Justification:
const client = new MongoClient(uri, {
maxPoolSize: 50,
minPoolSize: 5,
serverSelectionTimeoutMS: 3000
});
🔍 Behind the Question: Driver resource management and latency. ❌ The Red Flags: New client per request; unbounded pool sizes.
Q21: What are MongoDB change streams used for?
Technical Answer:
Change streams watch collections/databases for data changes (insert/update/delete) and emit events — enabling event-driven architectures, real-time sync to search/analytics, audit trails, and cache invalidation without polling. Works on replica sets and sharded clusters (with startAtOperationTime caveats). Use with resume tokens for at-least-once delivery.
Code/Syntax Justification:
const changeStream = db.collection("orders").watch()
changeStream.on("change", (change) => {
if (change.operationType === "insert") {
syncToSearchIndex(change.fullDocument)
}
})
🔍 Behind the Question: Event-driven patterns and real-time sync. ❌ The Red Flags: Polling when change streams exist; no resume token handling.
Q22: How do you implement MongoDB transactions in a distributed app?
Technical Answer:
Multi-document transactions (replica set 4.0+, sharded 4.2+) give ACID across documents: start session, startTransaction(), perform operations, commit or abort. Use transactions for money movements, order+inventory, or multi-doc consistency. Keep transactions short, retry TransientTransactionError / UnknownTransactionCommitResult on network failures.
Code/Syntax Justification:
const session = client.startSession()
try {
await session.withTransaction(async () => {
await db.collection("accounts").updateOne(
{ _id: aId }, { $inc: { balance: -100 } }, { session })
await db.collection("accounts").updateOne(
{ _id: bId }, { $inc: { balance: 100 } }, { session })
})
} catch (e) {
console.error("tx failed", e)
}
🔍 Behind the Question: ACID guarantees and retry patterns. ❌ The Red Flags: Long-running transactions; no retry on transient errors.
Q23: How do you handle large documents and the 16MB limit?
Technical Answer:
MongoDB caps documents at 16MB. For large payloads (files, blobs), store binary in GridFS (chunks + files collections) or external object storage (S3) and keep a reference. Design models to avoid unbounded arrays (use separate collections with pagination for comments/messages). Monitor maxSize issues during schema design.
Code/Syntax Justification:
// Store file metadata in Mongo, blob in S3
const fileRef = { s3_key: "uploads/x.pdf", size: 99999, type: "application/pdf" }
db.files.insertOne({ user_id: u, ...fileRef })
🔍 Behind the Question: Schema design around size limits. ❌ The Red Flags: Embedding large binary or unbounded arrays.
Q24: What are MongoDB aggregation stages and their order?
Technical Answer:
Pipeline stages transform documents: $match (filter early), $project (shape), $group (aggregate), $sort, $limit, $unwind (flatten arrays), $lookup (join), $facet (multi-pipeline). Order matters: $match/$limit first reduces work; use indexes for $match/$sort; $group is where most CPU goes.
Code/Syntax Justification:
db.orders.aggregate([
{ $match: { tenant_id: "t1", status: "paid" } },
{ $group: { _id: "$region", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
])
🔍 Behind the Question: Pipeline optimization and stage ordering.
❌ The Red Flags: $unwind before $match; missing index on $match fields.
Q25: How do you optimize MongoDB for a multi-tenant SaaS?
Technical Answer:
Key patterns: tenant_id in every document and first in every compound index; per-tenant queries always filtered by tenant_id; use $isolated-free (replica) queries with consistent reads; per-tenant rate limits and quotas; consider shard key by tenant or hashed; monitor hot spots (a tenant's high volume) with currentOp and per-tenant profiling. For hard isolation, per-tenant databases/collections.
Code/Syntax Justification:
// Profile slow queries per tenant
db.setProfilingLevel(1, { slowms: 100 })
// Find hot tenants
db.orders.aggregate([{ $group: { _id: "$tenant_id", count: { $sum: 1 } } },
{ $sort: { count: -1 } }, { $limit: 20 }])
🔍 Behind the Question: SaaS data isolation and hot-tenant detection. ❌ The Red Flags: Queries without tenant filter; no tenant-first indexes.
Q26: What is the difference between read preference and write concern?
Technical Answer:
Write concern controls acknowledgment/durability of writes (w:1 primary ack, w:majority majority ack, j:true journal). Read preference controls which replica serves reads (primary, primaryPreferred, secondary, secondaryPreferred, nearest). Use majority write concern for critical writes, read from secondary for read scaling (with eventual consistency).
Code/Syntax Justification:
// Strong write durability
db.orders.insertOne(doc, { writeConcern: { w: "majority", j: true } })
// Read from nearest replica (replica set)
db.orders.find(query).readPref("secondaryPreferred")
🔍 Behind the Question: Consistency/durability trade-offs.
❌ The Red Flags: w:1 for financial writes; reading stale data where linearizable needed.
Q27: How do you prevent and detect slow queries?
Technical Answer:
Enable profiling (slowms), monitor currentOp, use the Atlas/ops manager profiler, add indexes for missing-index queries, and set application-level timeouts. Common fixes: compound indexes for sort/range, avoiding $regex unanchored and $where (non-indexable), and keeping documents small.
Code/Syntax Justification:
// Find running ops with long durations
db.currentOp({ active: true, secs_running: { $gt: 5 } })
// Explain a query's index usage
db.orders.find({ tenant_id: "t1" }).sort({ created_at: -1 }).explain("executionStats")
🔍 Behind the Question: Query performance triage.
❌ The Red Flags: Ignoring COLLSCAN in explain; no profiling enabled.
Q28: What is MongoDB Atlas vs self-hosted vs DocumentDB?
Technical Answer:
- Atlas: fully managed MongoDB — automated backups, scaling, monitoring, global clusters; cost premium
- Self-hosted: full control, lower raw cost, but you own ops (backup, upgrades, monitoring, sharding)
- Amazon DocumentDB: MongoDB-compatible API on AWS (not real MongoDB) — managed, but diverges on features (transactions earlier, no true sharding initially, different perf profile); good if you already run AWS and need a compatible managed doc DB
Code/Syntax Justification:
Choose: Atlas for true MongoDB features/managed ops
DocumentDB for AWS-native managed + Mongo-compatible API
Self-host for cost control/compliance/air-gap
🔍 Behind the Question: Platform selection trade-offs. ❌ The Red Flags: Assuming DocumentDB is 100% MongoDB (feature gaps).
Q29: How do you back up and restore with minimal downtime?
Technical Answer:
Use continuous backups (Atlas) or oplog-based point-in-time recovery: base snapshot + oplog tailing. On self-hosted: mongodump (logical, slower, consistent with --oplog), filesystem snapshots (fast, needs coordinated lock), or Atlas continuous. Restore: restore base, replay oplog to target time, verify with data checks.
Code/Syntax Justification:
# Logical backup with oplog for PITR
mongodump --uri "$MONGODB_URI" --oplog --out /backup/$(date +%F)
# Restore
mongorestore --uri "$MONGODB_URI" --oplogReplay /backup/2026-01-01
🔍 Behind the Question: Backup strategy and RPO/RTO. ❌ The Red Flags: Only daily mongodump (RPO = 1 day); untested restores.
Q30: How do you do schema versioning in MongoDB?
Technical Answer:
Add a schema_version field; support multiple versions in code during rolling migrations. Use $set to add fields, backfill in batches (with write concern), and drop old fields after all clients upgrade. For sharded clusters, migrate slowly with startSession and TTL-aware batching. Keep migrations idempotent and test against a production-sized copy.
Code/Syntax Justification:
// Reader handles both versions
const doc = db.users.findOne({ _id })
if (doc.schema_version < 2) {
doc.email_verified = doc.email_verified ?? false // backfill at read
}
// Background migration job
db.users.find({ schema_version: { $lt: 2 } })
.forEach(u => db.users.updateOne({ _id: u._id },
{ $set: { schema_version: 2, email_verified: !!u.email_verified } }))
🔍 Behind the Question: Evolve schemas without downtime. ❌ The Red Flags: Forcing instant writes; no version field; destructive drops.
Senior / Principal — Real World Scenarios
Q31: Unbounded document growth — memory and performance degradation
Level: Senior
Scenario: A user_sessions collection stores one document per login with an embedded array of events. Active users accumulate thousands of events. Documents grow beyond 16MB MongoDB limit. Queries slow down and writes fail.
Impact: Writes fail with "document too large." Queries scan bloated documents. Memory pressure.
Root Cause: Unbounded embedded arrays grow forever. MongoDB documents have a 16MB size limit. Large documents also waste RAM (WiredTiger cache) and slow updates due to document relocation.
Simple explanation: A notebook page keeps getting taped with new notes. Eventually the page is too big to fit in the binder.
Technical Answer:
- Cap array size and evict old events (keep last N) or use a separate
eventscollection referenced by session ID. - Use TTL indexes to auto-expire old session documents (
expireAfterSeconds). - Store large arrays in a separate collection with references, not embedded, when unbounded.
- Monitor document size with
collStatsandavgObjSize.
Code/Syntax Justification:
// Cap session events array at last 100
db.user_sessions.updateOne(
{ userId },
{ $push: { events: { $each: [newEvent], $slice: -100 } } }
);
// TTL index: sessions expire 7 days after lastActivity
db.user_sessions.createIndex({ lastActivity: 1 }, { expireAfterSeconds: 7 * 86400 });
Workflow Diagram:
Login event arrives
|
v
Push event to user_sessions.events
|
v
$slice -100 keeps only latest 100 events
|
v
Document size stays bounded
|
v
TTL index expires old sessions automatically
🔍 Behind the Question: Document size limits, array growth, TTL indexes, WiredTiger cache pressure.
❌ The Red Flags: Embedding unbounded arrays; no TTL; ignoring avgObjSize and collStats.
Q32: Stale reads after write — read preference and replication lag
Level: Principal
Scenario: A user creates an order and immediately queries it from a secondary (read preference secondaryPreferred). The document is not yet replicated. The user sees "order not found."
Impact: Confusing read-your-writes inconsistency. Lost customer trust.
Root Cause: MongoDB replication is asynchronous. Writes go to primary; secondaries replicate with a lag. Reading from secondary before replication completes returns stale or missing data.
Simple explanation: You write in the primary notebook. The photocopy (secondary) is updated a moment later. Reading the photocopy too soon shows old content.
Technical Answer:
- Use read preference
primaryfor read-your-writes critical operations (order confirmation). - Use
secondaryPreferredonly for non-critical reads (analytics, recommendations). - For causal consistency, use
majoritywrite concern and read concernmajorityso reads see acknowledged writes. - Monitor replication lag with
db.serverStatus().repl.
Code/Syntax Justification:
# Critical read: primary (read-your-writes)
order = db.orders.with_options(read_preference=Primary()).find_one({"_id": order_id})
# Non-critical read: secondary (analytics)
stats = db.orders.with_options(read_preference=SecondaryPreferred()).aggregate([...])
# Majority write + read concern for consistency
db.orders.insert_one(doc, write_concern=WriteConcern("majority"))
Workflow Diagram:
Write to Primary
|
v
[Async replication to Secondary]
|
+-- lag small --> secondary soon consistent
|
+-- lag large --> secondary stale
Read from Secondary (too soon) --> MISSING data
Read from Primary --> always current (read-your-writes)
🔍 Behind the Question: Read preferences, write/read concern, replication lag, causal consistency.
❌ The Red Flags: Reading from secondary for user-facing read-your-writes; no write concern; ignoring replication lag.
Q33: Missing index — collection scan on high-traffic query
Level: Senior
Scenario: A query db.orders.find({ customerId: X }).sort({ createdAt: -1 }) takes 2 seconds on a 10-million-row orders collection. No index on customerId.
Impact: Slow API. High CPU. Collection scans (COLLSCAN) read every document.
Root Cause: No supporting index. MongoDB performs a collection scan and in-memory sort.
Simple explanation: Finding one customer's orders in a pile of 10 million unsorted receipts.
Technical Answer:
- Create a compound index:
{ customerId: 1, createdAt: -1 }to support both filter and sort. - Verify with
explain("executionStats")— look forIXSCANnotCOLLSCAN, and noSORTstage. - Monitor index usage with
$indexStats; drop unused indexes (write overhead). - Consider covered queries if only indexed fields are projected.
Code/Syntax Justification:
db.orders.createIndex({ customerId: 1, createdAt: -1 });
// Verify
db.orders.find({ customerId: 123 }).sort({ createdAt: -1 }).explain("executionStats")
// -> stage: IXSCAN, no COLLSCAN, no SORT
Workflow Diagram:
Query: customerId = X, sort createdAt desc
|
v
No Index Index {customerId:1, createdAt:-1}
| |
v v
COLLSCAN (read all 10M docs) IXSCAN (jump to customer X)
in-memory sort index already sorted by createdAt
| |
v v
Slow (2s) Fast (ms)
🔍 Behind the Question: Index design, explain plans, COLLSCAN vs IXSCAN, covered queries.
❌ The Red Flags: Indexing every field (write penalty); not verifying with explain; single-field index when compound needed for sort.
Q34: Split-brain / failover in replica set during election
Level: Principal
Scenario: A 3-member MongoDB replica set loses network connectivity between primary and one secondary. The isolated secondary cannot reach primary. After electionTimeoutMillis, remaining members elect a new primary. When the network heals, the old primary steps down but may have accepted divergent writes.
Impact: Brief write unavailability during election. Possible write divergence if old primary accepted writes after losing majority.
Root Cause: MongoDB uses Raft-like consensus. A primary needs majority to remain primary. Network partitions can cause elections and brief unavailability. Write concern majority prevents acknowledged writes on a minority partition.
Simple explanation: Three judges vote on a decision. If one is unreachable, the other two can still decide. When the third returns, they must re-sync.
Technical Answer:
- Use odd number of voting members (3 or 5) to avoid ties.
- Set
writeConcern: majorityso writes are only acknowledged when replicated to majority. - Set
electionTimeoutMillisappropriately (default 10s; tune for faster/slower failover). - Use
readConcern: majorityfor reads that must reflect acknowledged writes. - Avoid arbiter-only for critical data (arbiters vote but hold no data).
Code/Syntax Justification:
from pymongo import WriteConcern, ReadConcern
db.orders.with_options(
write_concern=WriteConcern("majority"),
read_concern=ReadConcern("majority"),
).insert_one(doc)
Workflow Diagram:
Network partition: Primary isolated from 1 secondary
|
v
Remaining 2 members hold election -> new primary elected
|
v
Old primary (minority) cannot get majority -> steps down (with majority write concern)
|
v
Network heals -> old primary rejoins as secondary, syncs oplog
|
v
Consistency restored
🔍 Behind the Question: Replica set elections, majority write concern, split-brain, failover.
❌ The Red Flags: Write concern 1 (acks on primary only) during partitions; even number of voters; no election timeout tuning.
Q35: Sharding strategy — hot shard and uneven distribution
Level: Principal
Scenario: A sharded orders collection uses customerId as shard key. A few "whale" customers generate 80% of traffic. Their shard becomes a hot spot while other shards are idle.
Impact: Hot shard overload. Uneven resource use. Queries for whale customers slow.
Root Cause: Poor shard key choice — high cardinality but skewed write/read distribution. MongoDB routes by shard key range/hash; skewed keys concentrate traffic.
Simple explanation: One cashier lane gets all the customers with big carts; other lanes are empty.
Technical Answer:
- Choose a shard key with high cardinality AND uniform distribution (e.g., hashed shard key on
customerId, or compound{ region: 1, customerId: 1 }). - Use hashed shard key to distribute writes randomly (loses range queries on that field).
- If already sharded poorly, reshard using
reshardCollectionor migrate chunks manually. - Monitor shard utilization with
sh.status()anddb.stats()per shard.
Code/Syntax Justification:
// Hashed shard key distributes writes evenly
sh.shardCollection("app.orders", { customerId: "hashed" });
// Or compound: region first for locality, customerId for cardinality
sh.shardCollection("app.orders", { region: 1, customerId: 1 });
Workflow Diagram:
Shard key customerId (range) Shard key customerId (hashed)
| |
v v
Whale customer -> Shard 1 (hot) Whale customer -> random shard
Whale customer -> Shard 1 (hot) Whale customer -> random shard
Other customers -> Shards 2,3 (idle) Other customers -> random shards
Uneven Even distribution
🔍 Behind the Question: Shard key selection, hashed vs ranged, hot shards, resharding.
❌ The Red Flags: Shard key with low cardinality or heavy skew; monotonic keys (insert hot spot); no shard utilization monitoring.
Senior / Principal — MongoDB Real World Scenarios (Continued)
Q36: Write concern majority — latency vs durability trade-off
Level: Senior
Scenario: A financial application writes transactions to MongoDB. Using write concern w: 1 (acknowledged by primary only). During a primary failover, acknowledged writes are lost because they hadn't replicated to secondaries. Customers dispute missing transactions.
Impact: Data loss. Financial discrepancy. Compliance violation.
Root Cause: Write concern w: 1 only requires primary acknowledgment. Writes not yet replicated to secondaries are lost if primary steps down before replication.
Simple explanation: You hand a letter to the postmaster (primary) who says "got it." But the postmaster hasn't sent it to the backup office (secondary). The postmaster leaves. The letter is lost.
Technical Answer:
- Use
w: "majority"for critical writes — acknowledged only when replicated to majority of voting members. - Trade-off: higher latency (wait for replication) but no acknowledged write loss.
- Use
w: 1only for non-critical data (analytics events, logs) where loss is acceptable. - Combine with
read_concern: "majority"for reads that must see acknowledged writes. - Monitor
wiredTiger.concurrentTransactionsand replication lag.
Code/Syntax Justification:
from pymongo import WriteConcern, ReadConcern
# Majority write + read concern for critical data
db.orders.with_options(
write_concern=WriteConcern("majority", wtimeout=5000),
read_concern=ReadConcern("majority"),
).insert_one(order_doc)
Workflow Diagram:
Write concern w:1: Write concern w:majority:
Primary acks immediately Primary waits for majority replication
| |
v v
Primary fails -> acknowledged write lost Primary fails -> write safe on secondaries
Data loss No data loss
| |
v v
Fix: w:majority + read_concern:majority
🔍 Behind the Question: Write concern, read concern, majority replication, durability vs latency, CAP theorem.
❌ The Red Flags: w:1 for financial/critical data; no read concern; not handling wtimeout errors.
Q37: Oplog exhaustion — replication breaks under high write volume
Level: Senior
Scenario: A high-write MongoDB replica set generates oplog entries faster than secondaries can apply them. The oplog (capped collection) wraps around and overwrites entries secondaries haven't applied yet. Secondaries fall behind and require full resync.
Impact: Replication broken. Secondaries stale. Full resync is slow and impacts primary performance.
Root Cause: Oplog size too small for write volume. Oplog wraps before secondaries copy entries.
Simple explanation: A notebook with 100 pages. You write 200 pages of notes. The notebook overwrites page 1 before your assistant has copied it. Your assistant's copy is incomplete.
Technical Answer:
- Size oplog large enough (typically 10% of disk or based on write volume × replication lag window).
- Monitor
oplog.logsize andreplSetGetStatussecondary lag. - Use
oplogMinRetentionHours(MongoDB 5.0+) to prevent premature overwriting. - Add more secondaries or shard to distribute write load.
- Alert when secondary oplog lag approaches oplog window.
Code/Syntax Justification:
// Check oplog size and usage
db.getReplicationInfo();
// Check secondary lag
rs.status().members.forEach(m => {
print(m.name + " lag: " + (m.optimeDate - m.secondaryDelayDate));
});
Workflow Diagram:
High write volume: With adequate oplog:
Oplog fills quickly Oplog retains entries long enough
| |
v v
Oplog wraps (overwrites unapplied) Secondaries copy all entries
| |
v v
Secondaries require full resync Replication healthy
🔍 Behind the Question: Oplog sizing, replication lag, oplogMinRetentionHours, secondary resync.
❌ The Red Flags: Small oplog for high write volume; no lag monitoring; not using oplogMinRetentionHours.
Q38: Change streams — missed events during consumer downtime
Level: Senior
Scenario: An application uses MongoDB change streams to sync data to Elasticsearch. The consumer goes down for 2 hours. Change stream events accumulate. When consumer restarts, it resumes from last resume token. Events during downtime are replayed. Duplicate sync operations.
Impact: Duplicate data in Elasticsearch. Processing overhead. Potential inconsistency.
Root Cause: Change streams resume from resume token but don't deduplicate. Events during downtime are replayed idempotently or not.
Simple explanation: A conveyor belt carries packages. You step away for 2 hours. Packages pile up. When you return, you process them all — including ones you already processed before leaving.
Technical Answer:
- Use resume token to resume change stream after downtime.
- Make consumers idempotent (use
_idor operation type to deduplicate). - For critical sync, use change streams + a durable queue (Kafka) as buffer.
- Monitor change stream lag and consumer processing rate.
- Consider
fullDocumentandfullDocumentBeforeChangefor complete event data.
Code/Syntax Justification:
import pymongo
pipeline = [{'$match': {'operationType': {'$in': ['insert', 'update', 'replace']}}}]
resume_token = None # load from durable storage
with db.collection.watch(pipeline, resume_after=resume_token) as stream:
for change in stream:
resume_token = change['_id'] # save durably after processing
process_change(idempotent=True) # deduplicate by _id
Workflow Diagram:
Consumer downtime: With idempotent consumer + resume token:
Change stream events accumulate Consumer goes down
| |
v v
Consumer restarts Consumer restarts, resumes from token
| |
v v
Replays all events Replays events, deduplicates by _id
| |
v v
Duplicates in downstream No duplicates
🔍 Behind the Question: Change streams, resume token, idempotent consumers, change stream lag.
❌ The Red Flags: Non-idempotent change stream consumer; not saving resume token; no change stream lag monitoring.
Q39: Schema validation — preventing bad data at insert
Level: Senior
Scenario: A MongoDB collection stores user profiles. A buggy service inserts documents missing required fields (email, age). Application crashes when reading missing fields. Data quality degrades.
Impact: Application errors. Bad data in database. Hard to clean up retroactively.
Root Cause: MongoDB's dynamic schema allows any document structure. No enforcement at insert time.
Simple explanation: A form with no required fields. People submit blank forms. The system breaks when it tries to read the missing email.
Technical Answer:
- Use JSON Schema validator on collection (
validatoroption incollModorcreateCollection). - Define required fields, types, minimum/maximum values, pattern matching.
- Set
validationLevel: "strict"(validate all inserts/updates) or "moderate" (validate only existing valid fields). - Set
validationAction: "error"(reject invalid writes) or "warn" (log but allow). - Combine with application-level validation for defense in depth.
Code/Syntax Justification:
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "age"],
properties: {
email: { bsonType: "string", pattern: "^[^@]+@[^@]+\\.[^@]+$" },
age: { bsonType: "int", minimum: 0, maximum: 150 },
status: { enum: ["active", "inactive"] }
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Workflow Diagram:
Without validation: With JSON Schema validation:
Insert missing email Insert missing email
| |
v v
Stored successfully Rejected: "missing required field: email"
| |
v v
App crashes reading email Bad data never enters database
🔍 Behind the Question: JSON Schema validation, validationLevel, validationAction, schema enforcement.
❌ The Red Flags: No collection validator; relying only on application validation; validationAction: warn for critical data.
Q40: TTL index — auto-expiring sessions and temporary data
Level: Senior
Scenario: A MongoDB collection stores user sessions. Sessions should expire after 30 minutes of inactivity. Without TTL, sessions accumulate forever. Collection grows unbounded. Queries slow down.
Impact: Unbounded collection growth. Slow queries. Wasted storage.
Root Cause: No automatic expiration mechanism. Documents never deleted unless explicitly removed.
Simple explanation: A whiteboard that never gets erased. Old notes pile up. You can't find new notes. Eventually the board is full.
Technical Answer:
- Create TTL index on
expireAtfield:createIndex({ expireAt: 1 }, { expireAfterSeconds: 0 }). - Set
expireAttocurrent_time + TTLwhen inserting document. - MongoDB background thread deletes expired documents (runs every 60 seconds).
- TTL delete is not exact — up to 60 seconds delay plus deletion time.
- Monitor
metrics.ttl.deletesand collection size.
Code/Syntax Justification:
from datetime import datetime, timedelta
# Create TTL index (once)
db.sessions.create_index("expireAt", expireAfterSeconds=0)
# Insert session expiring in 30 minutes
db.sessions.insert_one({
"user_id": "abc",
"data": {...},
"expireAt": datetime.utcnow() + timedelta(minutes=30)
})
Workflow Diagram:
TTL index: Without TTL:
Document inserted with expireAt Document inserted, no expiry
| |
v v
Background thread checks every 60s Document stays forever
| |
v v
expireAt < now -> delete Collection grows unbounded
Document removed Queries slow down
🔍 Behind the Question: TTL index, automatic expiration, background delete thread, TTL delete delay.
❌ The Red Flags: No TTL index; manually deleting expired documents (inefficient); expecting exact deletion time.
Q41: Aggregation pipeline — $lookup performance on large collections
Level: Senior
Scenario: An aggregation pipeline uses $lookup to join two large collections (orders + customers, 10M each). The pipeline takes minutes. $lookup performs a collection scan on the foreign collection for each document.
Impact: Slow aggregation. High CPU. Pipeline times out.
Root Cause: $lookup without indexes on foreign field performs nested loop scan (O(n×m)).
Simple explanation: Looking up each customer's address in a phone book by scanning every page for each order. 10 million orders × 10 million customers = too much work.
Technical Answer:
- Create index on foreign field in both collections (
customerIdin orders,_idin customers). - Use
$matchbefore$lookupto reduce documents. - Consider
$lookupwith pipeline for filtering joined documents. - For frequent joins, consider denormalizing (embed customer name in orders).
- Use
$unionWithor application-level joins if MongoDB$lookupis too slow.
Code/Syntax Justification:
# Slow: $lookup without index
pipeline = [
{"$lookup": {
"from": "customers",
"localField": "customerId",
"foreignField": "_id",
"as": "customer"
}}
]
# Fast: $match first, then $lookup with index
pipeline = [
{"$match": {"status": "pending"}}, # reduce to 1000 orders
{"$lookup": {
"from": "customers",
"localField": "customerId",
"foreignField": "_id",
"as": "customer"
}}
]
# Ensure indexes: db.orders.create_index("customerId"), db.customers.create_index("_id")
Workflow Diagram:
$lookup without index: $lookup with index + $match first:
For each order (10M): Match first (1000 orders)
Scan customers (10M) For each order (1000):
| Use index on customers._id
v |
O(n×m) = 10^14 operations O(n×log(m)) = fast
🔍 Behind the Question: $lookup performance, indexes on join fields, $match before $lookup, denormalization.
❌ The Red Flags: $lookup on large unindexed collections; no $match to reduce documents; not using indexes on foreign fields.
Q42: Read preference — secondary reads for analytics
Level: Senior
Scenario: An analytics dashboard runs heavy aggregation queries on MongoDB. These queries run on the primary, slowing down user-facing writes. Primary CPU saturates.
Impact: User-facing writes slow. Analytics and production workloads compete.
Root Cause: All reads go to primary. No read preference configured for analytics workloads.
Simple explanation: The cash register (primary) handles both customer checkout and inventory counting. Counting inventory slows down checkout.
Technical Answer:
- Use
read_preference: secondaryPreferredfor analytics/read-heavy workloads. - Use
primaryfor read-your-writes critical operations. - Use
secondaryonly when stale data is acceptable. - Combine with
read_concern: "local"or "majority" based on consistency needs. - Monitor replication lag — secondary reads may return stale data.
Code/Syntax Justification:
from pymongo import ReadPreference
# Analytics: read from secondary (stale OK)
analytics = db.orders.with_options(read_preference=ReadPreference.SECONDARY_PREFERRED)
result = analytics.aggregate([...])
# User-facing: read from primary (fresh)
user_data = db.orders.with_options(read_preference=ReadPreference.PRIMARY).find_one({"_id": id})
Workflow Diagram:
All reads on primary: Read preference split:
Analytics + user writes Primary: user writes + fresh reads
| |
v v
Primary CPU saturates Secondary: analytics (stale OK)
Checkout slows Primary: fast for users
🔍 Behind the Question: Read preference, secondary reads, replication lag, workload isolation.
❌ The Red Flags: All reads on primary for analytics; secondary reads for read-your-writes; ignoring replication lag.
Q43: Connection pool exhaustion — too many application connections
Level: Senior
Scenario: 50 application instances each open 100 MongoDB connections = 5000 connections. MongoDB maxIncomingConnections limit (default 65536 but practical limit lower) approached. New connections fail. Application errors.
Impact: Application can't connect to MongoDB. Widespread errors.
Root Cause: Each application instance maintains its own connection pool. Total connections exceed MongoDB capacity.
Simple explanation: 50 people each calling one receptionist at once. The phone line is busy. Nobody gets through.
Technical Answer:
- Use connection pooling with appropriate
maxPoolSize(e.g., 50-100 per instance). - Set
minPoolSizeto avoid connection churn. - Use
maxIdleTimeMSto close idle connections. - Consider MongoDB connection pooler or middleware for many instances.
- Monitor
metrics.cursor.openandconnections.current.
Code/Syntax Justification:
from pymongo import MongoClient
client = MongoClient(
"mongodb://host:27017",
maxPoolSize=50,
minPoolSize=10,
maxIdleTimeMS=30000,
waitQueueTimeoutMS=5000
)
Workflow Diagram:
50 app instances x 100 connections: Pooled connections:
5000 connections to MongoDB 50 instances x 10 connections = 500
| |
v v
Approaching connection limit Connections reused, no exhaustion
Connection failures Stable connection count
🔍 Behind the Question: Connection pooling, maxPoolSize, connection churn, MongoDB connection limits.
❌ The Red Flags: No connection pool limits; one connection per operation; not monitoring connection count.
Q44: Index usage — COLLSCAN vs IXSCAN
Level: Senior
Scenario: A query db.orders.find({ status: "pending", createdAt: { $gt: date } }) takes 10 seconds on 10M documents. explain("executionStats") shows COLLSCAN (collection scan) reading every document.
Impact: Slow queries. High CPU. Poor application performance.
Root Cause: No supporting index on the query fields. MongoDB scans every document.
Simple explanation: Finding all pending orders from last week in a pile of 10 million unsorted papers. You read every paper.
Technical Answer:
- Create compound index matching query pattern:
{ status: 1, createdAt: -1 }. - Use
explain("executionStats")to confirm IXSCAN (index scan) not COLLSCAN. - Index order matters — equality fields first, then range/sort fields.
- Monitor index usage with
$indexStats; drop unused indexes (write overhead). - Consider covered queries (projection only includes indexed fields).
Code/Syntax Justification:
// Create compound index
db.orders.createIndex({ status: 1, createdAt: -1 });
// Verify with explain
db.orders.find({ status: "pending", createdAt: { $gt: new Date("2026-01-01") } })
.explain("executionStats");
// Look for: "stage": "IXSCAN" not "COLLSCAN"
Workflow Diagram:
No index: Compound index {status:1, createdAt:-1}:
COLLSCAN (read all 10M docs) IXSCAN (jump to pending + date range)
| |
v v
10 seconds < 100ms
🔍 Behind the Question: Index usage, COLLSCAN vs IXSCAN, compound index order, explain plan.
❌ The Red Flags: COLLSCAN on large collections; no index on queried fields; not verifying with explain.
Q45: Covered queries — projection with indexed fields only
Level: Senior
Scenario: A query returns user_id and email from a 5M document users collection. The query fetches full documents from disk just to project two fields. Slow and memory-intensive.
Impact: Slow query. High disk I/O. Unnecessary data transfer.
Root Cause: Query fetches full documents even though only indexed fields are needed. No covered query optimization.
Simple explanation: You need a phone number from a contact card. You photocopy the entire card just to read one field.
Technical Answer:
- Create index covering all queried fields:
{ user_id: 1, email: 1 }. - Project only indexed fields:
{ _id: 0, user_id: 1, email: 1 }. - MongoDB serves query entirely from index (no document fetch) = covered query.
- Verify with explain:
stage: "IXSCAN"andstage: "PROJECTION_COVERED". - Monitor
docsExamined= 0 for covered queries.
Code/Syntax Justification:
# Covered query - all fields in index
db.users.create_index([("user_id", 1), ("email", 1)])
result = db.users.find(
{"user_id": "abc"},
{"_id": 0, "user_id": 1, "email": 1} # projection only indexed fields
).explain("executionStats")
# docsExamined: 0 (covered query)
Workflow Diagram:
Non-covered query: Covered query:
Fetch full document from disk Serve entirely from index
| |
v v
Read _id, user_id, email, address, ... Read user_id, email from index only
| |
v v
Project to user_id, email Return directly
docsExamined: 1 docsExamined: 0
🔍 Behind the Question: Covered queries, projection, index-only scans, docsExamined, explain.
❌ The Red Flags: Projecting non-indexed fields; fetching full documents unnecessarily; not checking docsExamined.
Q46: WiredTiger cache — cache pressure and eviction
Level: Principal
Scenario: MongoDB uses WiredTiger storage engine. The cache (default 50% of RAM) is too small for the working set. Pages are constantly evicted and re-read from disk. Query latency spikes.
Impact: Slow queries. High disk I/O. CPU spent on cache management.
Root Cause: WiredTiger cache smaller than working set (frequently accessed data).
Simple explanation: A desk with space for 10 papers. You need 50 papers for your work. You constantly swap papers between desk and filing cabinet. Slow.
Technical Answer:
- Size WiredTiger cache (
wiredTigerCacheSizeGB) to fit working set (not all data). - Monitor
wiredTiger.cache.tracked dirty bytes in cacheandpages read into cache. - If cache % full > 95% constantly, increase cache or reduce working set.
- Use
storage.wiredTiger.engineConfig.cacheSizeGBin config. - Consider more RAM or sharding if working set exceeds single node capacity.
Code/Syntax Justification:
# MongoDB config
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8 # ~50% of RAM, leave room for OS/file system cache
Workflow Diagram:
Cache too small: Cache sized for working set:
Working set > cache Working set fits in cache
| |
v v
Constant eviction + re-read Cache hit, no disk read
| |
v v
High disk I/O, slow queries Fast queries, low I/O
🔍 Behind the Question: WiredTiger cache, working set, cache eviction, cacheSizeGB, monitoring.
❌ The Red Flags: Cache too small for working set; not monitoring cache metrics; setting cache to 100% of RAM (starves OS).
Q47: Sharding — chunk migration and balancer
Level: Principal
Scenario: A sharded MongoDB cluster has uneven data distribution. One shard holds 80% of data. The balancer migrates chunks to rebalance. Chunk migration impacts primary performance on source shard.
Impact: Unbalanced cluster. Hot shard overload. Migration impact on production.
Root Cause: Poor shard key choice or data growth skew. Balancer migrating chunks during peak hours.
Simple explanation: One warehouse holds 80% of inventory. Workers try to move items to other warehouses. Moving items slows down the busy warehouse.
Technical Answer:
- Choose shard key with high cardinality and uniform write distribution (hashed or compound).
- Configure balancer window (
activeWindow) to migrate during off-peak hours. - Monitor
sh.status()for chunk distribution per shard. - Use
sh.disableBalancing()during critical operations, re-enable after. - Consider
sh.splitAt()orsh.splitFind()for manual chunk management.
Code/Syntax Justification:
// Check shard distribution
sh.status();
// Configure balancer window (e.g., 2am-4am)
sh.setBalancerState(true);
sh.stopBalancer();
sh.setBalancerWindow(2, 4); // 02:00-04:00
sh.startBalancer();
Workflow Diagram:
Unbalanced shards: Balanced with balancer window:
Shard 1: 80% data Shard 1: 33%, Shard 2: 33%, Shard 3: 33%
| |
v v
Shard 1 overloaded Balancer migrates chunks during 2-4am
Queries slow on shard 1 No production impact
🔍 Behind the Question: Sharding, shard key, balancer, chunk migration, chunk distribution.
❌ The Red Flags: Poor shard key (low cardinality, monotonic); balancer running during peak; not monitoring chunk distribution.
Q48: MongoDB version upgrade — feature compatibility version (FCV)
Level: Principal
Scenario: A team upgrades MongoDB from 4.4 to 5.0. New features (e.g., $unionWith, hedged reads) aren't available. The upgrade completed but FCV is still 4.4. Applications can't use new features.
Impact: New features unavailable. Upgrade incomplete.
Root Cause: MongoDB upgrades require setting Feature Compatibility Version (FCV) explicitly after binary upgrade. FCV controls which features are enabled.
Simple explanation: You install new software (MongoDB 5.0) but don't activate the new features (FCV still 4.4). The software runs in compatibility mode.
Technical Answer:
- Upgrade binaries first (rolling upgrade across replica set members).
- Set FCV after all members upgraded:
db.adminCommand({setFeatureCompatibilityVersion: "5.0"}). - FCV cannot be downgraded once set.
- Test on staging before setting FCV on production.
- Monitor
featureCompatibilityVersionindb.buildInfo().
Code/Syntax Justification:
// Check current FCV
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 });
// Set FCV (after all members upgraded to 5.0)
db.adminCommand({ setFeatureCompatibilityVersion: "5.0" });
Workflow Diagram:
Binary upgrade only: Binary upgrade + FCV set:
MongoDB 5.0 binaries MongoDB 5.0 binaries
| |
v v
FCV still 4.4 FCV set to 5.0
| |
v v
New features unavailable New features available ($unionWith, etc.)
🔍 Behind the Question: Feature Compatibility Version (FCV), rolling upgrade, version compatibility.
❌ The Red Flags: Setting FCV before all members upgraded; not testing FCV change; not knowing FCV controls feature availability.
Q49: MongoDB Atlas — auto-scaling and monitoring
Level: Senior
Scenario: A team uses MongoDB Atlas (managed). During traffic spike, instance CPU hits 95%. Atlas auto-scales the tier. But auto-scaling takes minutes. Application experiences slow queries during the window.
Impact: Temporary slowdown during scale-up. Possible timeouts.
Root Cause: Auto-scaling has propagation delay. Instance tier change takes time to provision.
Simple explanation: You call for more waiters during dinner rush. They arrive in 20 minutes. Customers wait in the meantime.
Technical Answer:
- Use Atlas auto-scaling with appropriate thresholds (CPU > 80% for 5 minutes).
- Set minimum instance tier high enough for baseline + burst.
- Use M30+ tiers for production (auto-scaling available on M30+).
- Monitor
cpu utilization,cache percent full,operations per second. - Consider provisioning ahead for predictable traffic spikes (events, sales).
Code/Syntax Justification:
# Atlas API: enable auto-scaling
# PATCH /groups/{GROUP_ID}/clusters/{CLUSTER_NAME}
{
"providerSettings": {
"autoScaling": {
"compute": {
"enabled": true,
"minInstanceSize": "M30",
"maxInstanceSize": "M60",
"scaleDownEnabled": false
}
}
}
}
Workflow Diagram:
Traffic spike: With auto-scaling:
CPU hits 95% CPU hits 80% for 5 min
| |
v v
Slow queries Auto-scaling triggered
| |
v v
Manual upgrade (minutes) New instance provisioned (minutes)
Slow during window Scale down disabled (keep burst capacity)
🔍 Behind the Question: Atlas auto-scaling, instance tiers, monitoring, proactive capacity planning.
❌ The Red Flags: No auto-scaling; min tier too low; not monitoring CPU/cache; scale-down enabled causing thrashing.
Q50: MongoDB backup — PITR with oplog and cloud manager
Level: Principal
Scenario: A production MongoDB database is accidentally deleted (db.collection.drop()). The team needs to recover to 10 minutes before the drop. They have nightly snapshots (last night) but lost 12 hours of data.
Impact: Data loss (12 hours). Recovery incomplete. Business impact.
Root Cause: Backup strategy relies on nightly snapshots only. No continuous backup/PITR.
Simple explanation: You back up your files every night at midnight. You delete a file at 2 PM. The last backup is from midnight. You lost 14 hours of work.
Technical Answer:
- Use MongoDB Cloud Manager/Ops Manager continuous backup (PITR).
- PITR uses snapshots + oplog to restore to any point in time.
- Can restore to specific timestamp (e.g., "10 minutes before the drop").
- Test restore regularly — backup is useless without verified restore.
- Monitor backup status and snapshot retention.
Code/Syntax Justification:
# MongoDB Cloud Manager: restore to point in time
# Via API or UI: select snapshot + oplog window
# Restore to "2026-01-15T13:50:00Z" (10 min before accidental drop at 14:00)
# Verify backup status
curl -u user:apiKey "https://cloud.mongodb.com/api/public/v1.0/groups/{GROUP_ID}/clusters/{CLUSTER_NAME}/backup"
Workflow Diagram:
Nightly snapshot only: PITR with oplog:
Snapshot at midnight Continuous snapshots + oplog
| |
v v
Drop at 2 PM Drop at 2 PM
| |
v v
Restore to midnight (lose 12 hours) Restore to 1:50 PM (lose 10 min)
Data loss Minimal data loss
🔍 Behind the Question: Backup strategy, PITR, oplog, restore testing, recovery point objective (RPO).
❌ The Red Flags: Nightly snapshots only; no PITR; not testing restores; unknown RPO/RTO.
Senior / Principal — MongoDB Real World Scenarios (Continued)
Q51: Write concern majority — latency vs durability trade-off
Level: Senior
Scenario: A financial application writes transactions to MongoDB. Using write concern w: 1 (acknowledged by primary only). During a primary failover, acknowledged writes are lost because they hadn't replicated to secondaries. Customers dispute missing transactions.
Impact: Data loss. Financial discrepancy. Compliance violation.
Root Cause: Write concern w: 1 only requires primary acknowledgment. Writes not yet replicated to secondaries are lost if primary steps down before replication.
Simple explanation: You hand a letter to the postmaster (primary) who says "got it." But the postmaster hasn't sent it to the backup office (secondary). The postmaster leaves. The letter is lost.
Technical Answer:
- Use
w: "majority"for critical writes — acknowledged only when replicated to majority of voting members. - Trade-off: higher latency (wait for replication) but no acknowledged write loss.
- Use
w: 1only for non-critical data (analytics events, logs) where loss is acceptable. - Combine with
read_concern: "majority"for reads that must see acknowledged writes. - Monitor
wiredTiger.concurrentTransactionsand replication lag.
Code/Syntax Justification:
from pymongo import WriteConcern, ReadConcern
# Majority write + read concern for critical data
db.orders.with_options(
write_concern=WriteConcern("majority", wtimeout=5000),
read_concern=ReadConcern("majority"),
).insert_one(order_doc)
Workflow Diagram:
Write concern w:1: Write concern w:majority:
Primary acks immediately Primary waits for majority replication
| |
v v
Primary fails -> acknowledged write lost Primary fails -> write safe on secondaries
Data loss No data loss
| |
v v
Fix: w:majority + read_concern:majority
🔍 Behind the Question: Write concern, read concern, majority replication, durability vs latency, CAP theorem.
❌ The Red Flags: w:1 for financial/critical data; no read concern; not handling wtimeout errors.
Q52: Oplog exhaustion — replication breaks under high write volume
Level: Senior
Scenario: A high-write MongoDB replica set generates oplog entries faster than secondaries can apply them. The oplog (capped collection) wraps around and overwrites entries secondaries haven't applied yet. Secondaries fall behind and require full resync.
Impact: Replication broken. Secondaries stale. Full resync is slow and impacts primary performance.
Root Cause: Oplog size too small for write volume. Oplog wraps before secondaries copy entries.
Simple explanation: A notebook with 100 pages. You write 200 pages of notes. The notebook overwrites page 1 before your assistant has copied it. Your assistant's copy is incomplete.
Technical Answer:
- Size oplog large enough (typically 10% of disk or based on write volume × replication lag window).
- Monitor
oplog.logsize andreplSetGetStatussecondary lag. - Use
oplogMinRetentionHours(MongoDB 5.0+) to prevent premature overwriting. - Add more secondaries or shard to distribute write load.
- Alert when secondary oplog lag approaches oplog window.
Code/Syntax Justification:
// Check oplog size and usage
db.getReplicationInfo();
// Check secondary lag
rs.status().members.forEach(m => {
print(m.name + " lag: " + (m.optimeDate - m.secondaryDelayDate));
});
Workflow Diagram:
High write volume: With adequate oplog:
Oplog fills quickly Oplog retains entries long enough
| |
v v
Oplog wraps (overwrites unapplied) Secondaries copy all entries
| |
v v
Secondaries require full resync Replication healthy
🔍 Behind the Question: Oplog sizing, replication lag, oplogMinRetentionHours, secondary resync.
❌ The Red Flags: Small oplog for high write volume; no lag monitoring; not using oplogMinRetentionHours.
Q53: Change streams — missed events during consumer downtime
Level: Senior
Scenario: An application uses MongoDB change streams to sync data to Elasticsearch. The consumer goes down for 2 hours. Change stream events accumulate. When consumer restarts, it resumes from last resume token. Events during downtime are replayed. Duplicate sync operations.
Impact: Duplicate data in Elasticsearch. Processing overhead. Potential inconsistency.
Root Cause: Change streams resume from resume token but don't deduplicate. Events during downtime are replayed idempotently or not.
Simple explanation: A conveyor belt carries packages. You step away for 2 hours. Packages pile up. When you return, you process them all — including ones you already processed before leaving.
Technical Answer:
- Use resume token to resume change stream after downtime.
- Make consumers idempotent (use
_idor operation type to deduplicate). - For critical sync, use change streams + a durable queue (Kafka) as buffer.
- Monitor change stream lag and consumer processing rate.
- Consider
fullDocumentandfullDocumentBeforeChangefor complete event data.
Code/Syntax Justification:
import pymongo
pipeline = [{'$match': {'operationType': {'$in': ['insert', 'update', 'replace']}}}]
resume_token = None # load from durable storage
with db.collection.watch(pipeline, resume_after=resume_token) as stream:
for change in stream:
resume_token = change['_id'] # save durably after processing
process_change(idempotent=True) # deduplicate by _id
Workflow Diagram:
Consumer downtime: With idempotent consumer + resume token:
Change stream events accumulate Consumer goes down
| |
v v
Consumer restarts Consumer restarts, resumes from token
| |
v v
Replays all events Replays events, deduplicates by _id
| |
v v
Duplicates in downstream No duplicates
🔍 Behind the Question: Change streams, resume token, idempotent consumers, change stream lag.
❌ The Red Flags: Non-idempotent change stream consumer; not saving resume token; no change stream lag monitoring.
Q54: Schema validation — preventing bad data at insert
Level: Senior
Scenario: A MongoDB collection stores user profiles. A buggy service inserts documents missing required fields (email, age). Application crashes when reading missing fields. Data quality degrades.
Impact: Application errors. Bad data in database. Hard to clean up retroactively.
Root Cause: MongoDB's dynamic schema allows any document structure. No enforcement at insert time.
Simple explanation: A form with no required fields. People submit blank forms. The system breaks when it tries to read the missing email.
Technical Answer:
- Use JSON Schema validator on collection (
validatoroption incollModorcreateCollection). - Define required fields, types, minimum/maximum values, pattern matching.
- Set
validationLevel: "strict"(validate all inserts/updates) or "moderate" (validate only existing valid fields). - Set
validationAction: "error"(reject invalid writes) or "warn" (log but allow). - Combine with application-level validation for defense in depth.
Code/Syntax Justification:
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "age"],
properties: {
email: { bsonType: "string", pattern: "^[^@]+@[^@]+\\.[^@]+$" },
age: { bsonType: "int", minimum: 0, maximum: 150 },
status: { enum: ["active", "inactive"] }
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Workflow Diagram:
Without validation: With JSON Schema validation:
Insert missing email Insert missing email
| |
v v
Stored successfully Rejected: "missing required field: email"
| |
v v
App crashes reading email Bad data never enters database
🔍 Behind the Question: JSON Schema validation, validationLevel, validationAction, schema enforcement.
❌ The Red Flags: No collection validator; relying only on application validation; validationAction: warn for critical data.
Q55: TTL index — auto-expiring sessions and temporary data
Level: Senior
Scenario: A MongoDB collection stores user sessions. Sessions should expire after 30 minutes of inactivity. Without TTL, sessions accumulate forever. Collection grows unbounded. Queries slow down.
Impact: Unbounded collection growth. Slow queries. Wasted storage.
Root Cause: No automatic expiration mechanism. Documents never deleted unless explicitly removed.
Simple explanation: A whiteboard that never gets erased. Old notes pile up. You can't find new notes. Eventually the board is full.
Technical Answer:
- Create TTL index on
expireAtfield:createIndex({ expireAt: 1 }, { expireAfterSeconds: 0 }). - Set
expireAttocurrent_time + TTLwhen inserting document. - MongoDB background thread deletes expired documents (runs every 60 seconds).
- TTL delete is not exact — up to 60 seconds delay plus deletion time.
- Monitor
metrics.ttl.deletesand collection size.
Code/Syntax Justification:
from datetime import datetime, timedelta
# Create TTL index (once)
db.sessions.create_index("expireAt", expireAfterSeconds=0)
# Insert session expiring in 30 minutes
db.sessions.insert_one({
"user_id": "abc",
"data": {...},
"expireAt": datetime.utcnow() + timedelta(minutes=30)
})
Workflow Diagram:
TTL index: Without TTL:
Document inserted with expireAt Document inserted, no expiry
| |
v v
Background thread checks every 60s Document stays forever
| |
v v
expireAt < now -> delete Collection grows unbounded
Document removed Queries slow down
🔍 Behind the Question: TTL index, automatic expiration, background delete thread, TTL delete delay.
❌ The Red Flags: No TTL index; manually deleting expired documents (inefficient); expecting exact deletion time.
Q56: Aggregation pipeline — $lookup performance on large collections
Level: Senior
Scenario: An aggregation pipeline uses $lookup to join two large collections (orders + customers, 10M each). The pipeline takes minutes. $lookup performs a collection scan on the foreign collection for each document.
Impact: Slow aggregation. High CPU. Pipeline times out.
Root Cause: $lookup without indexes on foreign field performs nested loop scan (O(n×m)).
Simple explanation: Looking up each customer's address in a phone book by scanning every page for each order. 10 million orders × 10 million customers = too much work.
Technical Answer:
- Create index on foreign field in both collections (
customerIdin orders,_idin customers). - Use
$matchbefore$lookupto reduce documents. - Consider
$lookupwith pipeline for filtering joined documents. - For frequent joins, consider denormalizing (embed customer name in orders).
- Use
$unionWithor application-level joins if MongoDB$lookupis too slow.
Code/Syntax Justification:
# Slow: $lookup without index
pipeline = [
{"$lookup": {
"from": "customers",
"localField": "customerId",
"foreignField": "_id",
"as": "customer"
}}
]
# Fast: $match first, then $lookup with index
pipeline = [
{"$match": {"status": "pending"}}, # reduce to 1000 orders
{"$lookup": {
"from": "customers",
"localField": "customerId",
"foreignField": "_id",
"as": "customer"
}}
]
# Ensure indexes: db.orders.create_index("customerId"), db.customers.create_index("_id")
Workflow Diagram:
$lookup without index: $lookup with index + $match first:
For each order (10M): Match first (1000 orders)
Scan customers (10M) For each order (1000):
| Use index on customers._id
v |
O(n×m) = 10^14 operations O(n×log(m)) = fast
Workflow Diagram:
$lookup without index: $lookup with index + $match first:
For each order (10M): Match first (1000 orders)
Scan customers (10M) For each order (1000):
| Use index on customers._id
v |
O(n×m) = 10^14 operations O(n×log(m)) = fast
🔍 Behind the Question: $lookup performance, indexes on join fields, $match before $lookup, denormalization.
❌ The Red Flags: $lookup on large unindexed collections; no $match to reduce documents; not using indexes on foreign fields.
Q57: Read preference — secondary reads for analytics
Level: Senior
Scenario: An analytics dashboard runs heavy aggregation queries on MongoDB. These queries run on the primary, slowing down user-facing writes. Primary CPU saturates.
Impact: User-facing writes slow. Analytics and production workloads compete.
Root Cause: All reads go to primary. No read preference configured for analytics workloads.
Simple explanation: The cash register (primary) handles both customer checkout and inventory counting. Counting inventory slows down checkout.
Technical Answer:
- Use
read_preference: secondaryPreferredfor analytics/read-heavy workloads. - Use
primaryfor read-your-writes critical operations. - Use
secondaryonly when stale data is acceptable. - Combine with
read_concern: "local"or "majority" based on consistency needs. - Monitor replication lag — secondary reads may return stale data.
Code/Syntax Justification:
from pymongo import ReadPreference
# Analytics: read from secondary (stale OK)
analytics = db.orders.with_options(read_preference=ReadPreference.SECONDARY_PREFERRED)
result = analytics.aggregate([...])
# User-facing: read from primary (fresh)
user_data = db.orders.with_options(read_preference=ReadPreference.PRIMARY).find_one({"_id": id})
Workflow Diagram:
All reads on primary: Read preference split:
Analytics + user writes Primary: user writes + fresh reads
| |
v v
Primary CPU saturates Secondary: analytics (stale OK)
Checkout slows Primary: fast for users
🔍 Behind the Question: Read preference, secondary reads, replication lag, workload isolation.
❌ The Red Flags: All reads on primary for analytics; secondary reads for read-your-writes; ignoring replication lag.
Q58: Connection pool exhaustion — too many application connections
Level: Senior
Scenario: 50 application instances each open 100 MongoDB connections = 5000 connections. MongoDB maxIncomingConnections limit (default 65536 but practical limit lower) approached. New connections fail. Application errors.
Impact: Application can't connect to MongoDB. Widespread errors.
Root Cause: Each application instance maintains its own connection pool. Total connections exceed MongoDB capacity.
Simple explanation: 50 people each calling one receptionist at once. The phone line is busy. Nobody gets through.
Technical Answer:
- Use connection pooling with appropriate
maxPoolSize(e.g., 50-100 per instance). - Set
minPoolSizeto avoid connection churn. - Use
maxIdleTimeMSto close idle connections. - Consider MongoDB connection pooler or middleware for many instances.
- Monitor
metrics.cursor.openandconnections.current.
Code/Syntax Justification:
from pymongo import MongoClient
client = MongoClient(
"mongodb://host:27017",
maxPoolSize=50,
minPoolSize=10,
maxIdleTimeMS=30000,
waitQueueTimeoutMS=5000
)
Workflow Diagram:
50 app instances x 100 connections: Pooled connections:
5000 connections to MongoDB 50 instances x 10 connections = 500
| |
v v
Approaching connection limit Connections reused, no exhaustion
Connection failures Stable connection count
🔍 Behind the Question: Connection pooling, maxPoolSize, connection churn, MongoDB connection limits.
❌ The Red Flags: No connection pool limits; one connection per operation; not monitoring connection count.
Q59: Index usage — COLLSCAN vs IXSCAN
Level: Senior
Scenario: A query db.orders.find({ status: "pending", createdAt: { $gt: date } }) takes 10 seconds on 10M documents. explain("executionStats") shows COLLSCAN (collection scan) reading every document.
Impact: Slow queries. High CPU. Poor application performance.
Root Cause: No supporting index on the query fields. MongoDB scans every document.
Simple explanation: Finding all pending orders from last week in a pile of 10 million unsorted papers. You read every paper.
Technical Answer:
- Create compound index matching query pattern:
{ status: 1, createdAt: -1 }. - Use
explain("executionStats")to confirm IXSCAN (index scan) not COLLSCAN. - Index order matters — equality fields first, then range/sort fields.
- Monitor index usage with
$indexStats; drop unused indexes (write overhead). - Consider covered queries (projection only includes indexed fields).
Code/Syntax Justification:
// Create compound index
db.orders.createIndex({ status: 1, createdAt: -1 });
// Verify with explain
db.orders.find({ status: "pending", createdAt: { $gt: new Date("2026-01-01") } })
.explain("executionStats");
// Look for: "stage": "IXSCAN" not "COLLSCAN"
Workflow Diagram:
No index: Compound index {status:1, createdAt:-1}:
COLLSCAN (read all 10M docs) IXSCAN (jump to pending + date range)
| |
v v
10 seconds < 100ms
🔍 Behind the Question: Index usage, COLLSCAN vs IXSCAN, compound index order, explain plan.
❌ The Red Flags: COLLSCAN on large collections; no index on queried fields; not verifying with explain.
Q60: Covered queries — projection with indexed fields only
Level: Senior
Scenario: A query returns user_id and email from a 5M document users collection. The query fetches full documents from disk just to project two fields. Slow and memory-intensive.
Impact: Slow query. High disk I/O. Unnecessary data transfer.
Root Cause: Query fetches full documents even though only indexed fields are needed. No covered query optimization.
Simple explanation: You need a phone number from a contact card. You photocopy the entire card just to read one field.
Technical Answer:
- Create index covering all queried fields:
{ user_id: 1, email: 1 }. - Project only indexed fields:
{ _id: 0, user_id: 1, email: 1 }. - MongoDB serves query entirely from index (no document fetch) = covered query.
- Verify with explain:
stage: "IXSCAN"andstage: "PROJECTION_COVERED". - Monitor
docsExamined= 0 for covered queries.
Code/Syntax Justification:
# Covered query - all fields in index
db.users.create_index([("user_id", 1), ("email", 1)])
result = db.users.find(
{"user_id": "abc"},
{"_id": 0, "user_id": 1, "email": 1} # projection only indexed fields
).explain("executionStats")
# docsExamined: 0 (covered query)
Workflow Diagram:
Non-covered query: Covered query:
Fetch full document from disk Serve entirely from index
| |
v v
Read _id, user_id, email, address, ... Read user_id, email from index only
| |
v v
Project to user_id, email Return directly
docsExamined: 1 docsExamined: 0
🔍 Behind the Question: Covered queries, projection, index-only scans, docsExamined, explain.
❌ The Red Flags: Projecting non-indexed fields; fetching full documents unnecessarily; not checking docsExamined.
Q61: WiredTiger cache — cache pressure and eviction
Level: Principal
Scenario: MongoDB uses WiredTiger storage engine. The cache (default 50% of RAM) is too small for the working set. Pages are constantly evicted and re-read from disk. Query latency spikes.
Impact: Slow queries. High disk I/O. CPU spent on cache management.
Root Cause: WiredTiger cache smaller than working set (frequently accessed data).
Simple explanation: A desk with space for 10 papers. You need 50 papers for your work. You constantly swap papers between desk and filing cabinet. Slow.
Technical Answer:
- Size WiredTiger cache (
wiredTigerCacheSizeGB) to fit working set (not all data). - Monitor
wiredTiger.cache.tracked dirty bytes in cacheandpages read into cache. - If cache % full > 95% constantly, increase cache or reduce working set.
- Use
storage.wiredTiger.engineConfig.cacheSizeGBin config. - Consider more RAM or sharding if working set exceeds single node capacity.
Code/Syntax Justification:
# MongoDB config
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8 # ~50% of RAM, leave room for OS/file system cache
Workflow Diagram:
Cache too small: Cache sized for working set:
Working set > cache Working set fits in cache
| |
v v
Constant eviction + re-read Cache hit, no disk read
| |
v v
High disk I/O, slow queries Fast queries, low I/O
🔍 Behind the Question: WiredTiger cache, working set, cache eviction, cacheSizeGB, monitoring.
❌ The Red Flags: Cache too small for working set; not monitoring cache metrics; setting cache to 100% of RAM (starves OS).
Q62: Sharding — chunk migration and balancer
Level: Principal
Scenario: A sharded MongoDB cluster has uneven data distribution. One shard holds 80% of data. The balancer migrates chunks to rebalance. Chunk migration impacts primary performance on source shard.
Impact: Unbalanced cluster. Hot shard overload. Migration impact on production.
Root Cause: Poor shard key choice or data growth skew. Balancer migrating chunks during peak hours.
Simple explanation: One warehouse holds 80% of inventory. Workers try to move items to other warehouses. Moving items slows down the busy warehouse.
Technical Answer:
- Choose shard key with high cardinality and uniform write distribution (hashed or compound).
- Configure balancer window (
activeWindow) to migrate during off-peak hours. - Monitor
sh.status()for chunk distribution per shard. - Use
sh.disableBalancing()during critical operations. Re-enable after. - Consider
sh.splitAt()orsh.splitFind()for manual chunk management.
Code/Syntax Justification:
// Check shard distribution
sh.status();
// Configure balancer window (e.g., 2am-4am)
sh.setBalancerState(true);
sh.stopBalancer();
sh.setBalancerWindow(2, 4); // 02:00-04:00
sh.startBalancer();
Workflow Diagram:
Unbalanced shards: Balanced with balancer window:
Shard 1: 80% data Shard 1: 33%, Shard 2: 33%, Shard 3: 33%
| |
v v
Shard 1 overloaded Balancer migrates chunks during 2-4am
Queries slow on shard 1 No production impact
🔍 Behind the Question: Sharding, shard key, balancer, chunk migration, chunk distribution.
❌ The Red Flags: Poor shard key (low cardinality, monotonic); balancer running during peak; not monitoring chunk distribution.
Q63: MongoDB version upgrade — feature compatibility version (FCV)
Level: Principal
Scenario: A team upgrades MongoDB from 4.4 to 5.0. New features (e.g., $unionWith, hedged reads) aren't available. The upgrade completed but FCV is still 4.4. Applications can't use new features.
Impact: New features unavailable. Upgrade incomplete.
Root Cause: MongoDB upgrades require setting Feature Compatibility Version (FCV) explicitly after binary upgrade. FCV controls which features are enabled.
Simple explanation: You install new software (MongoDB 5.0) but don't activate the new features (FCV still 4.4). The software runs in compatibility mode.
Technical Answer:
- Upgrade binaries first (rolling upgrade across replica set members).
- Set FCV after all members upgraded:
db.adminCommand({setFeatureCompatibilityVersion: "5.0"}). - FCV cannot be downgraded once set.
- Test on staging before setting FCV on production.
- Monitor
featureCompatibilityVersionindb.buildInfo().
Code/Syntax Justification:
// Check current FCV
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 });
// Set FCV (after all members upgraded to 5.0)
db.adminCommand({ setFeatureCompatibilityVersion: "5.0" });
Workflow Diagram:
Binary upgrade only: Binary upgrade + FCV set:
MongoDB 5.0 binaries MongoDB 5.0 binaries
| |
v v
FCV still 4.4 FCV set to 5.0
| |
v v
New features unavailable New features available ($unionWith, etc.)
🔍 Behind the Question: Feature Compatibility Version (FCV), rolling upgrade, version compatibility.
❌ The Red Flags: Setting FCV before all members upgraded; not testing FCV change; not knowing FCV controls feature availability.
Q64: MongoDB Atlas — auto-scaling and monitoring
Level: Senior
Scenario: A team uses MongoDB Atlas (managed). During traffic spike, instance CPU hits 95%. Atlas auto-scales the tier. But auto-scaling takes minutes. Application experiences slow queries during the window.
Impact: Temporary slowdown during scale-up. Possible timeouts.
Root Cause: Auto-scaling has propagation delay. Instance tier change takes time to provision.
Simple explanation: You call for more waiters during dinner rush. They arrive in 20 minutes. Customers wait in the meantime.
Technical Answer:
- Use Atlas auto-scaling with appropriate thresholds (CPU > 80% for 5 minutes).
- Set minimum instance tier high enough for baseline + burst.
- Use M30+ tiers for production (auto-scaling available on M30+).
- Monitor
cpu utilization,cache percent full,operations per second. - Consider provisioning ahead for predictable traffic spikes (events, sales).
Code/Syntax Justification:
# Atlas API: enable auto-scaling
# PATCH /groups/{GROUP_ID}/clusters/{CLUSTER_NAME}
{
"providerSettings": {
"autoScaling": {
"compute": {
"enabled": true,
"minInstanceSize": "M30",
"maxInstanceSize": "M60",
"scaleDownEnabled": false
}
}
}
}
Workflow Diagram:
Traffic spike: With auto-scaling:
CPU hits 95% CPU hits 80% for 5 min
| |
v v
Slow queries Auto-scaling triggered
| |
v v
Manual upgrade (minutes) New instance provisioned (minutes)
Slow during window Scale down disabled (keep burst capacity)
🔍 Behind the Question: Atlas auto-scaling, instance tiers, monitoring, proactive capacity planning.
❌ The Red Flags: No auto-scaling; min tier too low; not monitoring CPU/cache; scale-down enabled causing thrashing.
Q65: MongoDB backup — PITR with oplog and cloud manager
Level: Principal
Scenario: A production MongoDB database is accidentally deleted (db.collection.drop()). The team needs to recover to 10 minutes before the drop. They have nightly snapshots (last night) but lost 12 hours of data.
Impact: Data loss (12 hours). Recovery incomplete. Business impact.
Root Cause: Backup strategy relies on nightly snapshots only. No continuous backup/PITR.
Simple explanation: You back up your files every night at midnight. You delete a file at 2 PM. The last backup is from midnight. You lost 14 hours of work.
Technical Answer:
- Use MongoDB Cloud Manager/Ops Manager continuous backup (PITR).
- PITR uses snapshots + oplog to restore to any point in time.
- Can restore to specific timestamp (e.g., "10 minutes before the drop").
- Test restore regularly — backup is useless without verified restore.
- Monitor backup status and snapshot retention.
Code/Syntax Justification:
# MongoDB Cloud Manager: restore to point in time
# Via API or UI: select snapshot + oplog window
# Restore to specific timestamp (e.g., "10 minutes before the drop")
curl -u user:apiKey "https://cloud.mongodb.com/api/public/v1.0/groups/{GROUP_ID}/clusters/{CLUSTER_NAME}/backup"
Workflow Diagram:
Nightly snapshot only: PITR with oplog:
Snapshot at midnight Continuous snapshots + oplog
| |
v v
Drop at 2 PM Drop at 2 PM
| |
v v
Restore to midnight (lose 12 hours) Restore to 1:50 PM (lose 10 min)
Data loss Minimal data loss
🔍 Behind the Question: Backup strategy, PITR, oplog, restore testing, recovery point objective (RPO).
❌ The Red Flags: Nightly snapshots only; no PITR; not testing restores; unknown RPO/RTO.