MongoDB indexes


In MongoDB, indexes are used to improve the performance of queries by allowing the database to quickly find and retrieve the data that matches query conditions. Here’s an overview of the types of indexes MongoDB supports:

1. Single Field Index

  • Definition: An index on a single field in a document.
  • Usage: It's the simplest and most common type of index. You create a single field index to quickly locate documents based on that field.
  • Example:
    db.collection.createIndex({ "age": 1 });
    This creates an ascending index on the age field. Queries involving the age field will be faster.

2. Compound Index

  • Definition: An index on multiple fields in a document. The order of the fields in a compound index is important because it affects how MongoDB can optimize the queries.
  • Usage: Compound indexes are useful when you query based on multiple fields.
  • Example:
    db.collection.createIndex({ "lastName": 1, "firstName": 1 });
    This creates an index on both lastName and firstName in ascending order, optimizing queries that involve both fields or just the lastName.

3. Multikey Index

  • Definition: An index on fields that contain arrays. MongoDB automatically creates a multikey index if you index a field with array values.
  • Usage: Multikey indexes allow queries to match on individual array elements.
  • Example:
    db.collection.createIndex({ "tags": 1 });
    This creates an index on the tags field, which might contain arrays like ["tech", "science"]. The index allows efficient querying of documents that match any of the array elements.

4. Text Index

  • Definition: A specialized index for string fields to support text search within the database.
  • Usage: Text indexes enable full-text search capabilities in MongoDB, allowing you to search for words or phrases in string fields.
  • Example:
    db.collection.createIndex({ "description": "text" });
    This creates a text index on the description field, enabling queries like searching for specific keywords within text.

5. Geospatial Index

  • Definition: Indexes for supporting location-based queries like proximity searches, distance calculations, or geospatial operations.
  • Types:
    • 2d Index: For flat (planar) surface searches.
    • 2dsphere Index: For spherical geometry, which is used in most geospatial searches like finding nearby places on Earth.
  • Usage: Enables efficient querying of geospatial data, such as finding nearby locations within a certain radius.
  • Example:
    db.collection.createIndex({ "location": "2dsphere" });
    This creates a 2dsphere index on the location field to perform geospatial queries like finding points within a geographic area.