- Special data structures
- Store small portion of the data
- Ordered and easy to search efficiently
- Point to the document identity
Indexes improve query performance:
- Speed up queries
- Reduce disk 1/0
- Reduce resources required
- Support equality matches and range-based operations and return sorted results
Without indexes
- MongoDB reads all documents (collection scan)
- Sorts results in memory
With indexes
- MongoDB only fetches the documents identified by the index based on the query
- Returns results faster
<aside>
💡 There is one default index per collection, which includes only the _ id field
</aside>
<aside>
💡 Every query should use an index
</aside>
- If we insert or update documents, we need to update the index data structure
- Delete unnecessary or redundant indexes
Most common index types:
- Single field
- A single field index is an index on a single field of a document. MongoDB creates a single field index on theÂ
_id
 field by default, but additional indexes may be needed for other fields as well. A single field index can also be a multikey index if it operates on an array field.
- Compound
- MongoDB supports compound indexes, where a single index structure holds references to multiple fields within a collection's documents. A compound index is created by specifying the fields that the index should reference, followed by the order in which the fields should be sorted. The order of the fields in the index is important because it determines the order in which the documents are returned when querying the collection. A compound index can also be a multikey index if one of the fields is an array.