MongoDB Index Types: How to Create Single-Field and Compound Indexes?

MongoDB indexes are tools to accelerate queries, similar to book catalogs, which avoid full table scans. Single-field indexes target individual fields and are suitable for single-field filtering or sorting. The syntax is `db.collection.createIndex({fieldName: 1})` (1 for ascending order, -1 for descending order), and they only optimize queries involving that specific field. Compound indexes target multiple fields and follow the "left-prefix principle," meaning they can only optimize queries that include the leftmost field. For example, `{region:1, reg_time:-1}` only optimizes queries like `find({region: x})` or `find({region:x, reg_time: y})`. It is important to note that more indexes are not always better. Avoid indexing duplicate fields, low-selectivity fields (e.g., gender), or non-high-frequency queries. Indexes should be established moderately as needed, and reasonable planning is necessary to improve query efficiency without impacting write operations.

Read More
MongoDB Query Optimization: How Do Indexes Improve Query Efficiency?

MongoDB indexes are the core of query optimization, designed to address slow queries caused by full table scans when dealing with large datasets. Essentially, they are mapping structures (similar to directories) that associate field values with document locations, transforming queries from O(n) full table scans into O(log n) fast lookups and significantly improving efficiency. To create an index, use `createIndex({field: sortOrder})`, for example: `db.students.createIndex({age: 1})`. Common index types include single-field, compound (combining multiple fields with order adjusted based on query frequency), unique (ensuring field uniqueness), and text indexes (supporting fuzzy search). To verify if an index is effective, use `explain("executionStats")` to check the execution plan. Focus on `executionTimeMillis` (execution time) and `totalDocsExamined` (number of documents examined). If the latter equals the result count, the index is working. Important considerations: More indexes are not always better. Excessive indexes consume storage and slow down write operations. Prioritize indexing fields with high query frequency and avoid indexing fields with low query rates or high repetition. Properly using indexes ensures MongoDB maintains efficient responses as data grows.

Read More