Course Outline (Part 9)

Imagine you are looking for the word “Database” in a 1,000-page textbook. If the book doesn’t have an index at the back, you have to read every single page from beginning to end until you find it. This is incredibly slow.

In database terminology, reading every page is called a Collection Scan. If you have a million users in your database, and you run db.users.find({ username: "suresh" }), MongoDB has to look at every single one of those million documents to see if it matches.

To solve this massive performance problem, we use Indexes.


What is an Index?

An Index is a special data structure that stores a small portion of the collection’s data in an easy-to-traverse form.

Just like the index at the back of a textbook is sorted alphabetically, a MongoDB index is sorted mathematically. Because it is perfectly sorted, MongoDB can use highly efficient algorithms (like Binary Search) to find data in milliseconds, rather than minutes.

Note: The _id field is always indexed automatically by MongoDB when a collection is created.


Creating Indexes and Single Field Index

To create an index on a specific field, we use the createIndex() method. You pass it the field you want to index, and a 1 (for ascending order) or -1 (for descending order).

Let’s say we frequently search our users by their email address:

db.users.createIndex({ email: 1 })

Now, when we run db.users.find({ email: "test@example.com" }), MongoDB instantly looks at the email index, finds the exact location of that document on the hard drive, and fetches it instantly.


Compound Index

Often, you search by more than one field at a time. A Compound Index allows you to index multiple fields together.

Imagine an e-commerce store where users frequently filter by category and sort by price.

db.products.createIndex({ category: 1, price: -1 })

Important Rule (Prefix Equality): The order of the fields in a compound index matters immensely! The index { category: 1, price: -1 } can support queries on category AND price, or queries on just category. However, it cannot efficiently support queries on just price alone.


Unique Index

A Unique Index ensures that no two documents in a collection can have the same value for the indexed field. This is how you prevent duplicate usernames or email addresses during registration.

db.users.createIndex({ username: 1 }, { unique: true })

If you attempt to insert a second user with the same username, MongoDB will immediately throw a Duplicate Key Error.


Text Index

Standard indexes are great for exact matches, but terrible for searching within long paragraphs of text (like blog posts). A Text Index tokenizes and stems the words in a string, allowing for powerful search engine capabilities.

// Create a text index on the article's body
db.articles.createIndex({ body: "text" })

// Now you can search for words inside the article!
db.articles.find({ $text: { $search: "database optimization" } })

TTL Index (Time-To-Live)

A TTL Index is a magical index that automatically deletes documents after a certain amount of time has passed. This is perfect for expiring user sessions, OTP (One Time Password) codes, or temporary log files.

TTL indexes can only be applied to Date fields.

// Automatically delete the document 3600 seconds (1 hour) after the 'createdAt' date
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

Geospatial Index

If you are building an app like Uber or Tinder, you need to search for things based on physical location (e.g., “Find all restaurants within 5 miles of me”). MongoDB has native Geospatial Indexes for this exact purpose.

You use a 2dsphere index to calculate geometries on an earth-like sphere.

db.restaurants.createIndex({ location: "2dsphere" })

(Once created, you can use powerful operators like $near and $geoWithin to find locations!)


Hashed Index

A Hashed Index computes a mathematical hash of the value of a field. These are primarily used in Sharding (which we will cover in Module 19) to ensure data is distributed perfectly evenly across multiple servers.

db.users.createIndex({ _id: "hashed" })

Dropping Indexes

Indexes are not free. Every time you insert, update, or delete a document, MongoDB has to update the indexes as well. Having too many indexes will severely slow down your database’s write performance.

If you realize an index is no longer needed, you should remove it.

To see all current indexes:

db.users.getIndexes()

To drop (delete) a specific index by its name:

db.users.dropIndex("email_1")

Explain Plans

How do you know if your query is actually using your index, or if it is secretly doing a slow Collection Scan? You use the .explain() method!

Append .explain("executionStats") to any find() query to get a detailed performance report.

db.users.find({ email: "test@example.com" }).explain("executionStats")

Look at the output. If the winningPlan.stage says COLLSCAN, it means you are doing a slow Collection Scan and need to create an index. If it says IXSCAN (Index Scan), congratulations—your query is lightning fast!


Summary

Indexes are the single most important factor in database performance optimization.

  • Single / Compound Indexes speed up standard queries.
  • Unique Indexes enforce data integrity (no duplicate emails).
  • TTL Indexes automate the deletion of expired data.
  • Text & Geospatial Indexes unlock advanced search capabilities.
  • Always use .explain() to verify your indexes are actually working!

Now that you know how to query fast, let’s learn how to manipulate and transform that data in real-time using the immensely powerful Aggregation Framework in Module 9!

Discussion

Loading comments...