Search⌘ K
AI Features

Indexes: Single-Field, Compound, Text, and explain()

Explore how indexes improve query speed in MongoDB by reducing collection scans. Understand single-field, compound, and text indexes, their impact on query performance, and how to define them in Mongoose. Learn to use explain() to verify if queries use indexes effectively, helping you design scalable MongoDB applications.

A query that is fast on a hundred documents can become slow on a million. Indexing is often the difference. Without an index, MongoDB performs a collection scan (COLLSCAN): it reads every document to find matches. An index lets MongoDB locate matching documents without scanning the whole collection, similar to how a book index helps you find a topic without reading every page. This lesson covers common index types, how to define them in Mongoose, and how to verify them with explain() so you can tell whether a query will continue to perform as the collection grows.

Note: Index definitions go in the Mongoose schema; explain() examples run in the mongo shell against the seeded ecommerce collections.

To make the idea concrete, the next visual should contrast a full collection scan with an indexed lookup:

A collection scan reading every document vs. an index jumping to matches
A collection scan reading every document vs. an index jumping to matches
...