Support Online
Skip to main content

Using MongoDB Indexes: A Guide to Speeding Up Collection Queries

🚀 What Will You Learn in This Guide?

This guide teaches you how indexes (index/index) work in the MongoDB database, why they are important, and how they speed up query performance.
How to create single, unique, nested and compound indexes; You will also learn step by step how indexes are used in the query plan with the explain() method.

🧠 Technical Summary

Subject: Creation of indexes in MongoDB and techniques to increase query performance.
Purpose: To prevent queries from slowing down as the collection grows; Using index scan instead of full scan (Collection Scan).
Steps:

  1. Creating a sample database and collection
  2. Examine the indexless query plan
  3. Creating a single-field index
  4. Adding a unique index
  5. Applying index to nested fields
  6. Creating a compound index
  7. List and delete indexes

📦 Step 1 – Preparing the Sample Database

First, connect to the MongoDB shell with your administrator account:

mongo -u genixnode_admin -p --authenticationDatabase admin

➡️ Logs into MongoDB with authentication.

Now create a collection called peaks and add the sample data:

db.zirveler.insertMany([
{
"isim": "Everest",
"yukseklik": 8848,
"lokasyon": ["Nepal", "Çin"],
"tirmanislar": { "ilk": { "yil": 1953 }, "toplam": 5656 }
},
{
"isim": "K2",
"yukseklik": 8611,
"lokasyon": ["Pakistan", "Çin"],
"tirmanislar": { "ilk": { "yil": 1954 }, "toplam": 306 }
},
{
"isim": "Lhotse",
"yukseklik": 8516,
"lokasyon": ["Nepal", "Çin"],
"tirmanislar": { "ilk": { "yil": 1956 }, "toplam": 461 }
},
{
"isim": "Makalu",
"yukseklik": 8485,
"lokasyon": ["Çin", "Nepal"],
"tirmanislar": { "ilk": { "yil": 1955 }, "toplam": 361 }
}
])

➡️ Adds sample documents for five mountain peaks.

To view records:

db.zirveler.find()

⚡ Step 2 – Analyzing Indexless Query Performance

Inquire about peaks higher than 8700 meters:

db.zirveler.find({ "yukseklik": { $gt: 8700 } }).explain("executionStats")

➡️ Shows how the query is executed.

winningPlan.stage: "COLLSCAN" indicates that MongoDB scanned the entire collection. totalDocsExamined: 5 indicates that each document has been checked.


🔍 Step 3 – Creating a Single Field Index

Let's add an index to the height field:

db.zirveler.createIndex({ "yukseklik": 1 })

➡️ Creates an index in ascending order.

Run the same query again:

db.zirveler.find({ "yukseklik": { $gt: 8700 } }).explain("executionStats")

This time IXSCAN will appear and totalDocsExamined will drop from 5 to 1. Now MongoDB only reads matching documents — no full scans.


🔐 Step 4 – Creating a Unique Index

A unique index is used to prevent two documents with the same name:

db.zirveler.createIndex({ "isim": 1 }, { "unique": true })

➡️ It does not allow repeating values in the name field.

The following query no longer returns an error:

db.zirveler.insertOne({ "isim": "Everest", "yukseklik": 9000 })
Hata: E11000 duplicate key error collection: zirveler index: isim_1

🧩 Step 5 – Adding Indexes to Nested Fields

Indexes can also be added to embedded fields within the document. For example, tirmanislar.total field:

db.zirveler.createIndex({ "tirmanislar.toplam": 1 })

➡️ Adds an index to the total field in the embedded document.

The query will now run faster:

db.zirveler.find(
{ "tirmanislar.toplam": { $gt: 300 } }
).sort({ "tirmanislar.toplam": -1 }).explain("executionStats")

The result shows "stage": "IXSCAN" — MongoDB now uses the index.


🧱 Step 6 – Compound Indices

Composite indexes are ideal if you are querying by more than one field:

db.zirveler.createIndex(
{ "tirmanislar.ilk.yil": 1, "yukseklik": -1 }
)

➡️ The year of the first climb creates an index in ascending order and altitude in decreasing order.

Compound indexes are effective in queries starting from the leftmost field (leftmost prefix). In other words, it works first on the climbs.ilk.year field and then on the altitude field.


🌍 Step 7 – Adding Index to Multi-key Fields

If a field has more than one value (for example, a location field containing an array), MongoDB automatically creates a multi-key index.

db.zirveler.createIndex({ "lokasyon": 1 })

➡️ It keeps a separate index record for each country value.

Query example:

db.zirveler.find({ "lokasyon": "Nepal" }).explain("executionStats")

The output will include "isMultiKey": true.


🗂️ Step 8 – List and Remove Indexes

To list all indexes:

db.zirveler.getIndexes()

➡️ Shows all defined indexes.

To delete a specific index:

db.zirveler.dropIndex("yukseklik_1")

To clear all indexes:

db.zirveler.dropIndexes()

💬 Frequently Asked Questions (FAQ)

  1. Do too many indexes reduce performance?

Yes. Indexes are recalculated with each insert/update. Unnecessary indexes slow down writes.

  1. Which values ​​are important in the explain() method?

winningPlan.stage: COLLSCAN (collection scan) or IXSCAN (index scan).

totalDocsExamined: How many documents were examined.

nReturned: How many documents were returned.

  1. Can I edit indexes?

No, you can delete the existing index (dropIndex) and create it again.

  1. Is it possible to create indexes in the background?

Yes, to prevent the system from crashing in large collections:

db.zirveler.createIndex({ "alan": 1 }, { background: true })
  1. Which fields should I add indexes to?

Add indexes to frequently queried, filtered or sorted fields.


🎯 Result

In this guide, you learned the effect of indexes on query performance in MongoDB. Now you know how to create singular, unique, embedded, and composite indexes. Correct indexing makes a difference in performance on large data sets.