This guide covers essential MongoDB performance optimization concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.
Several factors influence MongoDB performance:
Query optimization involves several strategies:
// Analyze query performance
db.orders.find({
status: "completed",
customerId: "123",
orderDate: { $gte: new Date("2024-01-01") }
}).explain("executionStats")
// Optimize query with proper indexes
db.orders.createIndex({
status: 1,
customerId: 1,
orderDate: 1
})
// Use projection to limit fields
db.orders.find(
{ status: "completed" },
{ orderId: 1, total: 1, _id: 0 }
)
// Use covered queries
db.orders.find(
{ status: "completed" },
{ status: 1, orderId: 1, _id: 0 }
)
// Implement pagination
db.orders.find()
.sort({ orderDate: -1 })
.skip(20)
.limit(10)
// Use aggregation for complex queries
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
totalOrders: { $sum: 1 },
totalAmount: { $sum: "$total" }
}},
{ $sort: { totalAmount: -1 } }
])
Performance monitoring involves various tools and techniques:
// Check server status
db.serverStatus()
// Monitor current operations
db.currentOp()
// Check database stats
db.stats()
// Analyze collection stats
db.orders.stats()
// Monitor index usage
db.orders.aggregate([
{ $indexStats: {} }
])
// Check query performance
db.orders.find({
status: "completed"
}).explain("allPlansExecution")
// Monitor system metrics
db.adminCommand({
serverStatus: 1,
metrics: 1
})
Follow these best practices for optimal performance:
// 1. Connection pooling
const client = new MongoClient(uri, {
maxPoolSize: 50,
minPoolSize: 10,
maxIdleTimeMS: 30000
})
// 2. Write concern configuration
db.orders.insertOne({
orderId: "123",
total: 100
}, {
writeConcern: { w: "majority", wtimeout: 5000 }
})
// 3. Batch operations
db.orders.bulkWrite([
{ insertOne: { document: { orderId: "1" } } },
{ insertOne: { document: { orderId: "2" } } }
])
Production performance troubleshooting involves several steps:
// Identify slow queries
db.system.profile.find({
millis: { $gt: 100 }
}).sort({ millis: -1 })
// Check resource usage
db.serverStatus().mem
db.serverStatus().opcounters
// Analyze index usage
db.orders.aggregate([
{ $indexStats: {} }
])
// Optimize memory usage
db.adminCommand({
setParameter: 1,
internalQueryExecMaxBlockingSortBytes: 33554432
})
// Configure read preferences
db.orders.find().readPref("secondary")
// Implement caching
db.orders.find({
status: "completed"
}).hint({ status: 1 })
Continue your MongoDB interview preparation with: