Loading introduction
Loading stats
Loading about
Loading posts
Loading article
Skip to content
Md Nayeem Hossain
Explorer
home.tsx
mongodb-performance-optimization-guide.md
mongodb-performance-optimization-guide.md
blog.json

// Database

MongoDB Performance Optimization: Complete Guide

Learn advanced techniques to optimize MongoDB queries, indexes, and schema design for maximum performance.

Md Nayeem HossainDec 20, 202413 min read

MongoDB Performance Optimization#

MongoDB is often chosen for its flexibility, but that same flexibility can lead to performance pitfalls if you aren't careful. A slow query can bring your entire application to a halt.

In this guide, I'll cover the most effective strategies for optimizing MongoDB performance, focusing on indexing, query analysis, and schema design.

The Power of Indexes#

Indexes are the single most important factor in database performance. Without an index, MongoDB must perform a Collection Scan—scanning every single document in a collection to find a match. This is incredibly slow for large datasets.

An index creates a sorted data structure that allows MongoDB to find documents efficiently.

javascript
1// Create a single field index2// Good for queries like: db.users.find({ email: "..." })3db.users.createIndex({ email: 1 }, { unique: true });4 5// Create a compound index6// Good for queries like: db.orders.find({ status: "pending", createdAt: -1 })7// Order matters! This index supports sorting by createdAt for pending orders.8db.orders.createIndex({9  status: 1,10  createdAt: -111});

Analyzing Queries with explain()#

Never guess why a query is slow. Use the explain() command to tell you exactly how MongoDB is executing your query.

javascript
1db.orders.find({2  userId: "123",3  status: "completed"4}).explain("executionStats");

When you run this, look for the ISCAN stage. If you see COLLSCAN, it means you are missing an index and doing a full collection scan. Also check totalDocsExamined vs nReturned. If MongoDB examined 10,000 documents to return 5, your index is not effective.

Schema Design: Embedding vs Referencing#

In SQL, you normalize data (separate tables). In MongoDB, you often denormalize or embed data to avoid joins (lookups), which can be expensive.

Embedding (Good for 1-to-Few):

If a user has a few addresses, store them directly in the user document. This allows you to get the user and their addresses in a single read operation.

javascript
1{2  _id: "user123",3  name: "John",4  addresses: [5    { city: "New York", zip: "10001" },6    { city: "Boston", zip: "02111" }7  ]8}

Referencing (Good for 1-to-Many):

If a user has 10,000 orders, distinct documents are better. Arrays growing indefinitely will hit document size limits and slow down updates.

javascript
1// User document2{ _id: "user123", name: "John" }3 4// Order document5{ _id: "order999", userId: "user123", total: 50.00 }

Caching with Redis#

Even with perfect indexes, databases have limits. For read-heavy data that doesn't change often, adding a caching layer like Redis can reduce database load by 90% or more.

typescript
1// Simple cache pattern2async function getUser(id) {3  // 1. Check cache4  const cached = await redis.get(`user:${id}`);5  if (cached) return JSON.parse(cached);6 7  // 2. If miss, fetch from DB8  const user = await db.collection('users').findOne({ _id: id });9 10  // 3. Save to cache for next time (expire in 60s)11  if (user) await redis.setex(`user:${id}`, 60, JSON.stringify(user));12 13  return user;14}
#MongoDB#Database#Performance#NoSQL
OlderDocker Containerization: From Development to ProductionNewer Node.js Backend Architecture: Patterns for Production

Outline

  • MongoDB Performance Optimization
  • The Power of Indexes
  • Analyzing Queries with explain()
  • Schema Design: Embedding vs Referencing
  • Caching with Redis