#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
Question 20 of 27hard

How do you optimize MongoDB performance?

Performance tuning techniques.

What You'll Learn

  • Query optimization
  • Index strategies
  • Schema optimization

Query Optimization

Use Explain

code.jsJavaScript
db.users.find({ email: "john@example.com" }).explain("executionStats");

// Check these metrics:
// - totalDocsExamined vs nReturned
// - executionTimeMillis
// - stage: COLLSCAN (bad) vs IXSCAN (good)

Projection (Select Fields)

code.jsJavaScript
// Bad - fetches all fields
db.users.find({ status: "active" });

// Good - only needed fields
db.users.find({ status: "active" }, { name: 1, email: 1 });

Use Covered Queries

code.jsJavaScript
// Index covers the query entirely
db.users.createIndex({ email: 1, name: 1 });
db.users.find({ email: "john@example.com" }, { name: 1, _id: 0 });

Index Strategies

code.jsJavaScript
// Compound index order matters
// Supports: { a: 1 }, { a: 1, b: 1 }
// Does NOT support: { b: 1 }
db.collection.createIndex({ a: 1, b: 1 });

// ESR Rule: Equality, Sort, Range
db.orders.createIndex({ status: 1, createdAt: -1, total: 1 });

Schema Optimization

Avoid Large Arrays

code.jsJavaScript
// Bad - unbounded array
{ comments: [/* thousands of comments */] }

// Good - reference or bucket pattern
{ recentComments: [/* last 10 */], commentCount: 5000 }

Pre-aggregate Data

code.jsJavaScript
// Instead of counting on every read
{ viewCount: 15234 }  // Increment on write

Other Optimizations

  • Use connection pooling
  • Enable compression
  • Batch writes with bulkWrite
  • Use read replicas for reads
  • Monitor with MongoDB Compass