Mongodb Guide

What is Indexing in MongoDB

1. Definition

Indexing in MongoDB is a technique used to improve the speed of data retrieval operations by creating a data structure that stores a small portion of the collection’s data in an easy-to-search format.

2. Simple Understanding

👉 Think of an index like a book index. Instead of reading the whole book, you directly jump to the page you need.

3. When to Use

  • When collections have large amounts of data
  • When queries are slow
  • When searching or filtering frequently
  • When sorting data

4. Where it is Used

  • Search operations (find, findOne)
  • Sorting queries
  • Filtering large datasets
  • Backend APIs for faster response

5. Why We Use It

  • Improves query performance
  • Reduces database scan time
  • Faster data retrieval
  • Efficient handling of large data

6. How It Works

  • Creates a separate data structure
  • Stores field values with references to documents
  • MongoDB uses index instead of scanning full collection
  • Similar to key-value lookup

Basic Syntax

// Create index on name field
db.users.createIndex({ name: 1 });

// Create descending index
db.users.createIndex({ age: -1 });

Real Example

// Without index (slow)
db.users.find({ name: "Manaswini" });

// With index (fast)
db.users.createIndex({ name: 1 });

7. Types of Indexes

  • Single Field Index
  • Compound Index
  • Multikey Index (for arrays)
  • Text Index (for search)
  • Unique Index

8. Advantages

  • Faster queries
  • Efficient data retrieval
  • Improves performance for large datasets

9. Disadvantages

  • Uses extra memory
  • Slows down write operations (insert/update)
  • Too many indexes can reduce performance

Interview Points

  • Index improves read performance
  • Avoid full collection scan
  • Trade-off: faster reads vs slower writes
  • createIndex() is used to create indexes