MongoDB Indexing Interview Questions

Introduction

This guide covers essential MongoDB indexing concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.

Medium

1. What are indexes in MongoDB and why are they important?

Indexes in MongoDB are data structures that improve query performance:

  • Speed up query execution
  • Support efficient sorting
  • Enable unique constraints
  • Optimize data access patterns
Benefits:
  • Faster query execution
  • Reduced disk I/O
  • Better resource utilization
  • Improved application performance
Medium

2. What are the different types of indexes in MongoDB?

MongoDB supports various types of indexes:

1. Single Field Index
// Create a single field index
db.users.createIndex({ email: 1 })

// Query using the index
db.users.find({ email: "user@example.com" })
2. Compound Index
// 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") }
})
3. Text Index
// Create a text index
db.products.createIndex({ 
    name: "text", 
    description: "text" 
})

// Search using text index
db.products.find({
    $text: { $search: "smartphone" }
})
4. Geospatial Index
// 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
        }
    }
})
Hard

3. How do you optimize index usage in MongoDB?

Optimizing index usage involves several strategies:

1. Index Selection
// 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
})
2. Index Size Optimization
// Use partial indexes
db.orders.createIndex(
    { customerId: 1 },
    { partialFilterExpression: { status: "active" } }
)

// Use sparse indexes
db.users.createIndex(
    { email: 1 },
    { sparse: true }
)
Hard

4. What are the best practices for MongoDB indexing?

Follow these best practices for effective indexing:

Indexing Best Practices:
  • Create indexes to support your queries
  • Consider index size and memory usage
  • Monitor index usage and performance
  • Use compound indexes effectively
  • Implement partial indexes when appropriate
Implementation Examples
// 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 }
)
Hard

5. How do you handle index maintenance and monitoring?

Effective index maintenance involves monitoring and optimization:

1. Index Monitoring
// Check index usage
db.orders.aggregate([
    { $indexStats: {} }
])

// Monitor index size
db.orders.stats()

// Analyze query performance
db.orders.find({
    status: "completed"
}).explain("executionStats")
2. Index Maintenance
// Drop unused indexes
db.orders.dropIndex("indexName")

// Rebuild indexes
db.orders.reIndex()

// Check index fragmentation
db.orders.validate()

Next Steps

Continue your MongoDB interview preparation with: