Lesson 23 of 50 – Indexes in MongoDB
46%

Indexes in MongoDB

An index in MongoDB is a data structure that helps the database find documents more efficiently. Without a suitable index, MongoDB may need to scan many documents to find matching records. Indexes can improve query performance when they match the queries your application runs.

1. What Is an Index?

Imagine a book containing hundreds of pages. If there is no index, you may need to search page by page to find a topic. A book index helps you locate the topic quickly.

MongoDB indexes work in a similar way. They help MongoDB locate documents using indexed field values.

Example Collection
{
    _id: 1,
    name: "Rahul",
    age: 20,
    course: "Java"
}
{
    _id: 2,
    name: "Priya",
    age: 22,
    course: "Python"
}
{
    _id: 3,
    name: "Aman",
    age: 19,
    course: "Java"
}

If an application frequently searches for students by name, creating an index on the name field may improve those queries.

2. Why Are Indexes Important?

  • They can make matching documents faster to find.
  • They can improve sorting performance for suitable queries.
  • They can support efficient searches on frequently queried fields.
  • They can enforce uniqueness when a unique index is appropriate.
  • They can reduce the amount of data examined by some queries.

Indexes also have costs. They consume storage and require maintenance when indexed data changes. Too many unnecessary indexes can slow down writes.

3. The Default _id Index

MongoDB automatically creates a unique index on the _id field for a standard collection. This ensures that two documents in the same collection cannot have the same _id value.

Example
db.students.find({
    _id: 1
})

MongoDB can use the default _id index to locate a document by its ID.

View Existing Indexes
db.students.getIndexes()

This displays the indexes defined on the students collection, including the default _id index.

4. Create a Single-Field Index

A single-field index is an index on one field. Use createIndex() to create it.

Syntax
db.collection.createIndex({
    field: 1
})

Use 1 for ascending index order and -1 for descending index order.

Example: Index the Name Field
db.students.createIndex({
    name: 1
})

This creates an ascending index on the name field.

Query by Name
db.students.find({
    name: "Rahul"
})

MongoDB may use the index for this query if the query planner determines that it is beneficial.

5. Create a Descending Index

A descending index stores index keys in descending order.

Example
db.students.createIndex({
    age: -1
})

This creates a descending index on the age field.

Query Sorted by Age
db.students.find().sort({
    age: -1
})

MongoDB may use the index to support this sort. Whether it does so depends on the query and available indexes.

6. Create a Compound Index

A compound index contains multiple fields. The order of its fields matters because it affects which queries and sorts the index can support.

Example
db.students.createIndex({
    course: 1,
    age: -1
})

This creates an index on course in ascending order, followed by age in descending order.

Example Query
db.students.find({
    course: "Java"
}).sort({
    age: -1
})

This query matches the leading index field and sorts by the second field. The compound index may support both operations.

Compound indexes are particularly useful when their field order matches common query patterns.

7. Create a Unique Index

A unique index prevents duplicate indexed values from being stored, subject to the index's rules.

Example
db.students.createIndex(
    { email: 1 },
    { unique: true }
)

This creates a unique index on the email field.

Two documents cannot have the same indexed email value. Before creating a unique index, check existing data for duplicates and consider how missing or null values should be handled.

Example Documents
db.students.insertOne({
    name: "Rahul",
    email: "rahul@example.com"
})

Inserting another document with the same email will fail if the unique index is active.

8. Check Indexes with getIndexes()

Use getIndexes() to inspect the indexes on a collection.

Example
db.students.getIndexes()

The result includes index names, indexed fields, index directions, and applicable options.

Check Indexes After Creating One
db.students.createIndex({
    course: 1
})

db.students.getIndexes()

The output should include the new course index, provided the creation succeeded.

9. Drop an Index

If an index is no longer useful, you can remove it using dropIndex().

Example
db.students.dropIndex("name_1")

The default index name for { name: 1 } is commonly name_1, unless a custom name was specified.

Remove All Non-ID Indexes
db.students.dropIndexes()

This removes the collection's non-ID indexes. MongoDB does not allow you to drop the required default _id index.

Warning: Dropping an index can make queries slower. Check its usage before removing it.

10. Analyze a Query with explain()

The explain() method helps you inspect how MongoDB plans and executes a query.

Example
db.students.find({
    name: "Rahul"
}).explain("executionStats")

The output includes execution details such as the winning plan, documents examined, and keys examined.

  • IXSCAN generally indicates an index scan.
  • COLLSCAN indicates a collection scan.
  • totalDocsExamined shows how many documents were examined.
  • totalKeysExamined shows how many index keys were examined.

A collection scan is not always a problem. For small collections or queries that return many documents, using an index may not be more efficient.

11. Indexing Best Practices

  • Create indexes for frequently used query patterns.
  • Use compound indexes when their field order supports common filters and sorts.
  • Avoid creating unnecessary indexes.
  • Remember that indexes consume storage.
  • Indexes add work to insert, update, and delete operations.
  • Use explain("executionStats") to investigate query performance.
  • Measure performance using realistic data and workloads.
  • Consider unique indexes when values must be unique.

12. Practical Assignment

Create a collection named practice_indexes and insert these documents:

db.practice_indexes.insertMany([
    {
        _id: 1,
        name: "Rahul",
        age: 22,
        course: "Java",
        email: "rahul@example.com"
    },
    {
        _id: 2,
        name: "Priya",
        age: 19,
        course: "Python",
        email: "priya@example.com"
    },
    {
        _id: 3,
        name: "Aman",
        age: 21,
        course: "Java",
        email: "aman@example.com"
    },
    {
        _id: 4,
        name: "Neha",
        age: 20,
        course: "HTML",
        email: "neha@example.com"
    }
])
Complete these tasks:
  1. Display all existing indexes.
  2. Create an ascending index on name.
  3. Create a descending index on age.
  4. Create a compound index on course and age.
  5. Create a unique index on email.
  6. Run a query that finds students by name and inspect it using explain("executionStats").
  7. Remove the name index using dropIndex().
  8. Display the remaining indexes.

Run the insertion command only once, or clear the test collection before inserting the same sample data again.

🧠 Quick Quiz

1. Which method creates an index?




2. Which index prevents duplicate indexed values?




3. Which method helps inspect a query execution plan?