What is Indexing?

Indexing is a technique used to improve the performance of database queries. By creating indexes on specific fields, you enable MongoDB to quickly locate and retrieve data without scanning the entire collection.

Creating Indexes

  • createIndex() Method:
    • Creates an index on the specified field(s) in a collection.

    • Example:

        db.collectionName.createIndex({ fieldName: 1 });
        
    • Here, { fieldName: 1 } specifies an ascending index. Use -1 for descending order.

Types of Indexes

Single Field Index

  • Description: An index on a single field.

  • Example:

      db.collectionName.createIndex({ name: 1 });
      

Compound Index

  • Description: An index on multiple fields.
  • Example:
  db.collectionName.createIndex({ field1: 1, field2: -1 });
  
  • This index will be useful for queries that filter or sort based on both field1 and field2.

Multi-Key Index

  • Description: An index on fields that hold an array of values.
  • Example:
  db.collectionName.createIndex({ tags: 1 });
  
  • This index is used for queries that need to search within arrays.

Geospatial Index

  • Description: An index for geospatial queries to work with location data.
  • Example:
  db.collectionName.createIndex({ location: "2dsphere" });
  
  • The 2dsphere index is used for spherical geometry queries, such as finding documents within a certain radius.

Query Optimization with Indexes

Indexes improve query performance by allowing MongoDB to quickly locate documents without scanning the entire collection. When creating indexes:

  • Analyze Queries: Use the explain() method to understand how queries are executed and whether indexes are being utilized.
  • Monitor Index Usage: Regularly monitor and review index performance and usage to ensure optimal query performance.
  • Avoid Over-Indexing: While indexes improve read performance, they can slow down write operations. Ensure that you index only those fields that are frequently used in queries.

Example: Using explain()

  • Query Execution Plan:
  db.collectionName.find({ name: "Alice" }).explain("executionStats");
  
  • Output:

    • The output provides detailed information about how MongoDB executed the query, including whether an index was used.

Summary

  • Indexing: Improves query performance by allowing faster data retrieval.
  • Single Field Index: Index on one field.
  • Compound Index: Index on multiple fields.
  • Multi-Key Index: Index on array fields.
  • Geospatial Index: Index for location-based queries.
  • Query Optimization: Use indexes to enhance query efficiency and monitor their performance.