0
0
MongoDBquery~5 mins

Why indexes are critical for performance in MongoDB

Choose your learning style9 modes available
Introduction

Indexes help MongoDB find data quickly without looking at every document. This makes searching much faster.

When you want to find specific records fast, like searching for a user by email.
When you have a large collection and want to speed up queries.
When you sort data often and want the sorting to be quick.
When you want to enforce uniqueness, like no two users having the same username.
Syntax
MongoDB
db.collection.createIndex({ field: 1 })

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

Indexes can be created on one or multiple fields.

Examples
Creates an index on the email field in ascending order.
MongoDB
db.users.createIndex({ email: 1 })
Creates an index on orderDate in descending order to speed up recent order queries.
MongoDB
db.orders.createIndex({ orderDate: -1 })
Creates a compound index on category (ascending) and price (descending) to speed up queries filtering by category and sorting by price.
MongoDB
db.products.createIndex({ category: 1, price: -1 })
Sample Program

This example inserts three users, creates an index on the email field, then finds the user with email 'bob@example.com'. The index helps MongoDB find Bob quickly.

MongoDB
db.users.insertMany([
  { name: "Alice", email: "alice@example.com" },
  { name: "Bob", email: "bob@example.com" },
  { name: "Carol", email: "carol@example.com" }
])
db.users.createIndex({ email: 1 })
db.users.find({ email: "bob@example.com" })
OutputSuccess
Important Notes

Indexes speed up read queries but can slow down writes because the index must be updated.

Too many indexes can use extra disk space and memory.

Use indexes thoughtfully on fields you query often.

Summary

Indexes make searching data faster by avoiding full collection scans.

Create indexes on fields you query or sort by frequently.

Balance the number of indexes to keep write performance good.