MongoDB Creating Indexes


In MongoDB, indexes can be created and dropped as needed to optimize query performance. Here’s how you can manage indexes:

1. Creating Indexes

You can create indexes using the createIndex() method. MongoDB allows you to create various types of indexes based on your needs, such as single-field, compound, multikey, text, and geospatial indexes.

Syntax:

db.collection.createIndex({ <field1>: <order>, <field2>: <order>, ... }, { <options> })
  • <field>: The field(s) you want to index. For a single field, specify one field. For a compound index, specify multiple fields.
  • <order>: The order of the index, 1 for ascending and -1 for descending.
  • <options>: Optional settings like unique index, background creation, etc.

Example 1: Creating a Single-Field Index

db.users.createIndex({ "age": 1 });

This creates an ascending index on the age field in the users collection.

Example 2: Creating a Compound Index

db.orders.createIndex({ "customerId": 1, "orderDate": -1 });

This creates an index on both customerId (ascending) and orderDate (descending) in the orders collection.

Example 3: Creating a Unique Index

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

This creates a unique index on the email field, ensuring that no two documents have the same value in this field.

Example 4: Creating a Text Index

db.articles.createIndex({ "content": "text" });

This creates a text index on the content field to support text search in the articles collection.

Example 5: Creating a Geospatial Index

db.locations.createIndex({ "coordinates": "2dsphere" });

This creates a geospatial index on the coordinates field to handle location-based queries.

2. Dropping Indexes

Indexes can be dropped when they are no longer needed or if they are not improving performance. The dropIndex() method is used to drop a specific index, and dropIndexes() can be used to drop all indexes in a collection.

Syntax:

db.collection.dropIndex({ <field>: <order> })

Example 1: Dropping a Single Index

db.users.dropIndex({ "age": 1 });

This removes the index on the age field in the users collection.

Example 2: Dropping All Indexes

db.orders.dropIndexes();

This drops all indexes on the orders collection except the default _id index.

Example 3: Dropping an Index by Name

Each index in MongoDB has a name, and you can drop an index by referencing its name. You can retrieve the index names using the getIndexes() method.

  1. List indexes:
    db.collection.getIndexes();
  2. Drop the index by name:
    db.collection.dropIndex("index_name");

3. Options When Creating Indexes

When creating indexes, you can also provide several options to customize the behavior:

  • unique: Ensures that all values for the indexed field(s) are unique.

    db.collection.createIndex({ "email": 1 }, { unique: true });
  • background: Creates the index in the background, which allows operations on the collection to continue during index creation.

    db.collection.createIndex({ "age": 1 }, { background: true });
  • sparse: Only indexes documents that contain the indexed field.

    db.collection.createIndex({ "phoneNumber": 1 }, { sparse: true });
  • expireAfterSeconds: Used to create a TTL (Time-to-Live) index, which automatically removes documents after a specified time.

    db.collection.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 });

Summary

  • Creating an Index: Use the createIndex() method to create indexes on fields to improve query performance.
  • Dropping an Index: Use dropIndex() or dropIndexes() to remove unwanted indexes.
  • Customization: MongoDB supports several options like unique, background, and sparse to customize the behavior of indexes.