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