Mongodb Guide

Types of Indexes in MongoDB

1. Definition

MongoDB provides different types of indexes to optimize query performance. Each type is designed for specific use cases such as searching, sorting, or handling complex data structures.

2. When to Use

  • When queries are slow
  • When working with large datasets
  • When filtering, sorting, or searching data
  • When optimizing database performance

3. Types of Indexes

  • Single Field Index → Index on one field
  • Compound Index → Index on multiple fields
  • Multikey Index → Index on array fields
  • Text Index → For text search
  • Hashed Index → For hashed values (sharding)
  • Unique Index → Ensures unique values
  • TTL Index → Automatically deletes data after time
  • Geospatial Index → For location-based queries

4. Basic Syntax

// Single Field Index
db.users.createIndex({ name: 1 });

// Compound Index
db.users.createIndex({ name: 1, age: -1 });

// Text Index
db.posts.createIndex({ content: "text" });

// Unique Index
db.users.createIndex({ email: 1 }, { unique: true });

5. Real Example

// Faster search by name
db.users.createIndex({ name: 1 });

// Search posts by text
db.posts.createIndex({ title: "text", description: "text" });

// Ensure unique email
db.users.createIndex({ email: 1 }, { unique: true });

6. Explanation

  • Different indexes serve different purposes
  • Indexes improve read performance
  • Choosing correct index is important
  • Too many indexes can slow down writes

7. Advantages

  • Faster queries
  • Efficient data retrieval
  • Optimized database performance

8. Disadvantages

  • Consumes extra storage
  • Slows down insert/update operations
  • Requires proper planning

Interview Points

  • Common types: Single, Compound, Text, Unique
  • Indexes improve read performance
  • Too many indexes hurt performance
  • Choose index based on query pattern