This guide covers essential MongoDB indexing concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.
Indexes in MongoDB are data structures that improve query performance:
MongoDB supports various types of indexes:
// Create a single field index
db.users.createIndex({ email: 1 })
// Query using the index
db.users.find({ email: "user@example.com" })
// Create a compound index
db.orders.createIndex({
customerId: 1,
orderDate: -1
})
// Query using the compound index
db.orders.find({
customerId: "123",
orderDate: { $gte: new Date("2024-01-01") }
})
// Create a text index
db.products.createIndex({
name: "text",
description: "text"
})
// Search using text index
db.products.find({
$text: { $search: "smartphone" }
})
// Create a 2dsphere index
db.locations.createIndex({
location: "2dsphere"
})
// Query nearby locations
db.locations.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: 1000
}
}
})
Optimizing index usage involves several strategies:
// Analyze query patterns
db.orders.find({
status: "completed",
customerId: "123",
orderDate: { $gte: new Date("2024-01-01") }
}).explain("executionStats")
// Create optimal compound index
db.orders.createIndex({
status: 1,
customerId: 1,
orderDate: 1
})
// Use partial indexes
db.orders.createIndex(
{ customerId: 1 },
{ partialFilterExpression: { status: "active" } }
)
// Use sparse indexes
db.users.createIndex(
{ email: 1 },
{ sparse: true }
)
Follow these best practices for effective indexing:
// 1. Create indexes in background
db.orders.createIndex(
{ orderDate: 1 },
{ background: true }
)
// 2. Use covered queries
db.orders.createIndex({
customerId: 1,
orderDate: 1,
total: 1
})
// 3. Implement TTL indexes
db.sessions.createIndex(
{ lastAccess: 1 },
{ expireAfterSeconds: 3600 }
)
// 4. Use unique indexes
db.users.createIndex(
{ email: 1 },
{ unique: true }
)
Effective index maintenance involves monitoring and optimization:
// Check index usage
db.orders.aggregate([
{ $indexStats: {} }
])
// Monitor index size
db.orders.stats()
// Analyze query performance
db.orders.find({
status: "completed"
}).explain("executionStats")
// Drop unused indexes
db.orders.dropIndex("indexName")
// Rebuild indexes
db.orders.reIndex()
// Check index fragmentation
db.orders.validate()
Continue your MongoDB interview preparation with: