Introduction to Indexing

Learn what indexes are in MongoDB and how they improve query performance by quickly locating documents, reducing resource load, and supporting sorting and uniqueness in large datasets.

What is an index?

An index is a data structure that improves the speed and efficiency of data retrieval operations. It acts like a roadmap for the database engine, allowing it to quickly locate documents without scanning the entire collection.

Imagine trying to find a specific topic in a large book. Without an index, we'd need to flip through every page. With an index, we can jump directly to the right page. In MongoDB, indexes function similarly; they store a subset of the data in an optimized format to make lookups faster.

Default index

Every MongoDB collection automatically includes an index on the _id field. This guarantees fast access when querying by document ID. This index is created by default, ensures each document's uniqueness, and allows for fast, efficient lookups.

If indexes didn't exist, querying against _id would require MongoDB to search every document line by line to find a match. But with indexing, it can directly jump to the required document.

See the illustration below, where the search is optimized when queried against the following _id value: ObjectId("60c72b2f9b1d8f5a3f6e8c1a").