Indexes help MongoDB find data quickly without looking at every document. They work like a sorted list that points to where data lives.
0
0
How MongoDB indexes work (B-tree mental model)
Introduction
When you want to find documents fast by a specific field, like searching users by email.
When you need to sort query results quickly, like showing products by price.
When you want to enforce uniqueness, like making sure usernames are not repeated.
When you want to speed up queries on large collections without scanning all documents.
Syntax
MongoDB
db.collection.createIndex({ field: 1 })Use 1 for ascending order and -1 for descending order.
Indexes are stored as B-trees internally to keep data sorted and allow fast searching.
Examples
Creates an ascending index on the email field to speed up email searches.
MongoDB
db.users.createIndex({ email: 1 })Creates a descending index on the price field to quickly sort products from high to low.
MongoDB
db.products.createIndex({ price: -1 })Creates a unique index on username to prevent duplicate usernames.
MongoDB
db.users.createIndex({ username: 1 }, { unique: true })Sample Program
This example inserts some products, creates an ascending index on price, then finds all products sorted by price.
MongoDB
use shop
db.products.insertMany([
{ name: "Pen", price: 1.5 },
{ name: "Notebook", price: 3.0 },
{ name: "Eraser", price: 0.5 }
])
db.products.createIndex({ price: 1 })
db.products.find().sort({ price: 1 })OutputSuccess
Important Notes
Indexes speed up queries but take extra space and slow down writes a bit.
B-tree structure means MongoDB keeps index keys sorted and balanced for fast lookups.
Use indexes wisely on fields you query often.
Summary
Indexes in MongoDB use B-tree structures to keep data sorted and searchable fast.
Creating an index on a field helps queries and sorting on that field run quickly.
Unique indexes prevent duplicate values in a field.