Speeding Up Queries with Indexes

Understand indexes, create and inspect them, remove them when needed, and use explain to check query execution.

🎯 Introduction

We have been performing CRUD operations on a user collection containing only a few documents, so every query feels fast. Real collections can contain hundreds of thousands or millions of documents, and the same find query can perform very differently depending on indexes.

By the end, you will understand what indexes are and why they improve queries, create, inspect, and remove them, and use explain to verify index usage. This is an important step toward using MongoDB effectively.

These examples were written and tested with MongoDB 8.0 (Docker image mongo:8) and run in mongosh. If you are not connected, run:
docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin
Then switch to the example database with use blog_demo and reuse the user collection.

🧱 Why Indexes Matter

How does MongoDB locate the data when you run db.user.find({ username: 'Zhang San' })?

Without an index, it examines documents one by one, checking whether username equals 'Zhang San' until it has scanned the collection. This is a collection scan (COLLSCAN): every document must be examined.

Imagine searching for a passage in a book. Without a table of contents, you turn pages from the beginning, taking longer as the book grows. With a table of contents, you can locate the page and turn straight to it. An index serves a similar purpose for a collection.

You have already used an index: MongoDB automatically creates an index on _id for each collection, making lookups by _id efficient. Indexes on other fields must be created explicitly.

🛠 Creating and Inspecting Indexes

Use createIndex with a document specifying the field to index:

db.user.createIndex({ username: 1 });

1 specifies ascending index order; -1 specifies descending order. Both directions can support queries on a single field. For these introductory examples, use 1.

The command returns username_1, the automatically generated index name combining the field name and direction.

To list the collection's indexes, use getIndexes():

db.user.getIndexes();

You should see _id_, the built-in index on _id, and the username_1 index you just created.

To remove an index you no longer need, pass its name to dropIndex:

db.user.dropIndex('username_1');
Dropping an index does not delete documents; it removes the lookup structure. Queries may fall back to a collection scan. Check whether queries depend on it before removing it, or production endpoints may suddenly become slower.

✨ Checking Index Usage with explain

Do not guess whether a query uses an index. MongoDB's explain method shows the execution plan. Append .explain('executionStats') to the query:

db.user.find({ username: 'Zhang San' }).explain('executionStats');

The result is lengthy, but two key details are enough to get started:

  • The stage entries in winningPlan describe query execution. COLLSCAN means a collection scan; IXSCAN means an index scan.
  • The document count in executionStats tells you how many documents were examined. A lower number means less scanning.

Try this comparison yourself:

  1. Run explain before creating the index. The plan contains COLLSCAN, and the examined-document count equals the collection's document count.
  2. Create the index with db.user.createIndex({ username: 1 }).
  3. Run the same explain again. Look for IXSCAN and a smaller examined-document count.

With very little data, the timing difference may be hard to notice. The examined-document count still shows the difference: using an index avoids scanning the whole collection, and the benefit grows with the dataset.


💡 Unique Indexes: Preventing Duplicate Values

Some fields, such as usernames or phone numbers, must be unique. A regular index speeds up queries without preventing duplicates. Add { unique: true } to createIndex to create a unique index and let the database enforce uniqueness:

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

After creating it, inserting an existing username produces an error:

db.user.insertOne({ username: 'Zhang San', age: 26, city: 'Beijing' });
// Error: E11000 duplicate key error

The error means the unique index constraint was violated. This is useful for usernames and phone numbers: database-level enforcement is simpler and more reliable than querying for duplicates before every insert.

Before creating a unique index on existing data, check for duplicate values; duplicates cause index creation to fail. The _id index is itself unique, so documents cannot share the same _id.

🪤 More Indexes Are Not Always Better

If indexes are fast, why not index every field? Because indexes have a cost.

Returning to the book analogy, every new chapter requires updating the table of contents. Similarly, inserts, updates, and deletes require MongoDB to maintain the relevant indexes. More indexes mean:

  • More maintenance for writes, which can slow them down.
  • More memory and disk space for the indexes themselves.

Index fields used frequently in query filters. If login queries use username, index it. A field queried only a few times a year may not need one. Indexes should be chosen for your workload.


❓ Questions and Answers

Q1: What does 1 mean in createIndex({ username: 1 })? What about -1?

1 means ascending and -1 means descending, controlling the order of indexed values. For single-field queries, either direction works. Direction becomes more relevant when sorting by multiple fields; you do not need to explore that yet.

Q2: Will queries use an index automatically after I create it?

MongoDB chooses the execution plan automatically, without special query syntax. When the filter matches an indexed field, that index is available to the planner. Use explain to check which plan was selected.

Q3: Why does my explain result still show COLLSCAN?

Two common causes are that the index was not created successfully, which you can check with getIndexes(), or the query uses a different field, such as filtering by city when the index is on username.

Q4: Do unique and regular indexes conflict? Do I need both?

They do not inherently conflict, but you do not need both for the same lookup. A unique index also supports efficient queries, so one unique index on that field is sufficient.

Q5: Does dropping an index delete the data too?

No. An index is a lookup structure. Removing it changes how queries locate documents, while the documents remain intact. deleteOne and deleteMany delete data; dropIndex does not.


🧪 Exercises

Exercise 1: Create an ascending index on city in user, then list the indexes to confirm it exists.

// Write your code here

Exercise 2: Use explain('executionStats') to compare queries by username and by age. Assuming only username is indexed, which stages do you see, and why do they differ?

// Write your code here

🎉 You now understand MongoDB indexes! Next, we will use aggregation pipelines, combining stages such as $match and $group to calculate grouped statistics directly in MongoDB.