Indexing is the principal mechanism for improving query performance in MongoDB. Without indexes, MongoDB performs a collection scan, examining every document in a collection to satisfy a query. By creating efficient B-tree data structures on specific fields, indexes allow MongoDB to locate matching documents directly. However, indexes consume additional storage and memory, and they slow down write operations, so they should be created strategically based on actual query patterns.
Several index types address different use cases. A single field index is created on one field, such as db.users.createIndex({ email: 1 }), where 1 indicates ascending order and -1 indicates descending. MongoDB automatically creates a single field index on the _id field. Compound indexes include multiple fields in a single index, and the order of fields matters: they support queries that match a prefix of the indexed fields, following the ESR rule (Equality, Sort, Range) for optimal field ordering. Multikey indexes are automatically created when indexing a field that holds an array, producing separate index entries for each array element, though a compound index cannot include more than one array field.
Specialized indexes serve more targeted needs. Text indexes support full-text search on string content and are queried with the $text and $search operators; each collection can have at most one text index, but it can span multiple fields. TTL, or Time-To-Live, indexes automatically remove documents after a specified number of seconds, making them ideal for session data, logs, and temporary records. Wildcard indexes, introduced in version 4.2, index all fields or all subfields of a field, which is particularly useful for polymorphic schemas with dynamic or unknown field names. To evaluate performance, the explain() method reveals whether an index was used (an IXSCAN is preferable to a COLLSCAN), how many documents were examined, and execution time. When both the query filter and projection include only indexed fields, the result is a covered query that can be satisfied entirely from the index without reading any documents, achieving totalDocsExamined: 0.