DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Mastering MongoDB Indexing: Performance Optimization and Best Practices

Indexing in MongoDB


1. What are indexes, and why are they used?

Indexes are special data structures that store a subset of a collection's data in a format that supports efficient query execution.

Purpose:

  • Speed up data retrieval.
  • Improve query performance, especially for large datasets.
  • Reduce the need for full collection scans.

Example: Without an index, searching for documents involves scanning every document in the collection, which can be time-consuming for large datasets.


2. How do you create an index in MongoDB?

Indexes are created using the createIndex method.

Syntax:

db.collection.createIndex({ field: order })
Enter fullscreen mode Exit fullscreen mode
  • order:
    • 1: Ascending index.
    • -1: Descending index.

Example: Create an index on the age field in ascending order:

db.users.createIndex({ age: 1 })
Enter fullscreen mode Exit fullscreen mode

3. What is a compound index?

A compound index includes multiple fields, allowing queries to use the index when filtering or sorting by multiple fields.

Syntax:

db.collection.createIndex({ field1: order, field2: order })
Enter fullscreen mode Exit fullscreen mode

Example: Create a compound index on age and name:

db.users.createIndex({ age: 1, name: 1 })
Enter fullscreen mode Exit fullscreen mode
  • Used when queries involve multiple fields, e.g., find({ age: 25, name: "Alice" }).

4. How can you list all indexes on a collection?

Use the getIndexes method to list all indexes.

Syntax:

db.collection.getIndexes()
Enter fullscreen mode Exit fullscreen mode

Example:

db.users.getIndexes()
Enter fullscreen mode Exit fullscreen mode
  • Displays the default _id index and any additional indexes created.

5. What is a unique index in MongoDB?

A unique index ensures that all values in the indexed field are unique. This is often used to enforce constraints like unique usernames or email addresses.

Syntax:

db.collection.createIndex({ field: 1 }, { unique: true })
Enter fullscreen mode Exit fullscreen mode

Example: Create a unique index on email:

db.users.createIndex({ email: 1 }, { unique: true })
Enter fullscreen mode Exit fullscreen mode
  • If a duplicate value is inserted, MongoDB throws an error.

6. How do you drop an index?

Use the dropIndex method to delete an index.

Syntax:

db.collection.dropIndex("index_name")
Enter fullscreen mode Exit fullscreen mode

Example: Drop an index named age_1:

db.users.dropIndex("age_1")
Enter fullscreen mode Exit fullscreen mode
  • To drop all indexes except _id, use:
  db.collection.dropIndexes()
Enter fullscreen mode Exit fullscreen mode

7. Explain the purpose of text indexes.

Text indexes enable full-text search capabilities in MongoDB.

Features:

  • Used for searching strings in a collection.
  • Supports search for terms, phrases, or partial matches.

Syntax:

db.collection.createIndex({ field: "text" })
Enter fullscreen mode Exit fullscreen mode

Example: Create a text index on the description field:

db.products.createIndex({ description: "text" })
Enter fullscreen mode Exit fullscreen mode
  • Use $text in queries to perform text searches:
  db.products.find({ $text: { $search: "laptop" } })
Enter fullscreen mode Exit fullscreen mode

8. What are hashed indexes in MongoDB?

Hashed indexes distribute data across a collection by hashing the values of the indexed field.

Purpose:

  • Optimized for equality searches, like find({ field: value }).
  • Not suitable for range queries.

Syntax:

db.collection.createIndex({ field: "hashed" })
Enter fullscreen mode Exit fullscreen mode

Example: Create a hashed index on the user_id field:

db.users.createIndex({ user_id: "hashed" })
Enter fullscreen mode Exit fullscreen mode

9. How does the $explain method help in analyzing index performance?

The $explain method provides detailed information about how MongoDB executes a query, including whether and how indexes are used.

Syntax:

db.collection.find(query).explain("executionStats")
Enter fullscreen mode Exit fullscreen mode

Example: Analyze query execution for age search:

db.users.find({ age: 25 }).explain("executionStats")
Enter fullscreen mode Exit fullscreen mode
  • Key metrics include execution time, index usage, and documents scanned.

10. What is the impact of indexes on write operations?

Indexes can slow down write operations (inserts, updates, and deletes) because MongoDB must update the indexes in addition to the data.

Impacts:

  1. Increased overhead for maintaining index structures.
  2. Slower write performance with multiple or complex indexes.

Best Practices:

  • Create indexes selectively based on query requirements.
  • Avoid unnecessary or redundant indexes.
  • Regularly monitor and optimize indexes using tools like $explain.

Indexes are essential for improving query performance but should be used judiciously to balance read and write efficiency.

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)