Indexes 在 MongoDB 中通过让数据库无需扫描整个 collection 即可找到文档来加速查询 — 就像在 relational databases 中一样。没有索引,查询会执行 collection scan(检查每个文档);有了索引,查询就会很快。MongoDB 支持多种索引类型。
Creating 和 using indexes
db..({ : });
db..({ : });
db..({ : });
db..();
Indexes 在 MongoDB 中通过让数据库无需扫描整个 collection 即可找到文档来加速查询 — 就像在 relational databases 中一样。没有索引,查询会执行 collection scan(检查每个文档);有了索引,查询就会很快。MongoDB 支持多种索引类型。
db..({ : });
db..({ : });
db..({ : });
db..();
默认的 _id 字段总是被索引的。您可以在经常查询、排序或过滤的字段上添加索引。
// a compound index on multiple fields — order matters!
db.users.createIndex({ country: 1, age: -1 });
// helps: { country: ? }, { country: ?, age: ? } (leftmost prefix)
// does NOT help: { age: ? } alone
Compound indexes 涵盖多个字段上的查询,但 字段顺序很重要(索引支持使用其字段的最左前缀的查询 — 需要理解的关键规则)。
Single field → { field: 1 }
Compound → { a: 1, b: -1 } (multiple fields)
Multi-key → automatically created when indexing an ARRAY field (indexes each element)
Text → text search on string content
Geospatial → 2dsphere for location queries
Hashed → for hashed sharding
TTL → { createdAt: 1 } with expireAfterSeconds → auto-delete old docs
Unique → { email: 1 }, { unique: true } → enforce uniqueness
Partial/Sparse → index only some documents
✓ Indexes speed up reads dramatically (collection scan → index lookup)
✗ But they consume storage and SLOW DOWN writes (each write updates indexes)
→ Index what you query frequently; don't over-index (hurts writes). Use explain()
to verify queries use indexes (look for COLLSCAN = bad, IXSCAN = good).
索引是 MongoDB 性能中最重要的主题之一 — 它们是加快查询速度的主要工具,其原理与 relational databases 相似,因此理解它们是编写高性能 MongoDB 应用程序的必要知识。
没有索引,查询需要执行 collection scans(检查每个文档 — 当集合增长时速度慢得令人震惊),而索引可以实现快速查找 — 通常决定查询耗时毫秒还是秒。
了解如何在经常查询、排序或过滤的字段上创建索引是基础知识。Compound indexes(覆盖多字段查询)很重要,尤其是 字段顺序很重要 这一规则(索引支持使用其字段的最左前缀的查询 — 这是设计有效的 compound indexes 的关键概念)。
了解 MongoDB 相关的索引类型是有价值的:multi-key indexes(自动索引数组元素 — 鉴于 MongoDB 的数组密集文档很重要)、TTL indexes(自动过期旧文档 — 对 sessions、logs、临时数据很有用)、unique indexes(强制唯一性)、用于专门查询的 text 和 geospatial indexes,以及 partial/sparse indexes。
理解 trade-off(索引加快读取但消耗存储空间并减慢写入速度,因此索引您查询的内容但不要过度索引)并使用 explain() 验证查询使用索引(COLLSCAN = 坏的扫描,IXSCAN = 好的索引使用)是优化的关键实用技能。
由于查询性能至关重要且正确索引是最具影响力的 MongoDB 优化方式,理解索引 — 它们如何工作、compound index 排序、MongoDB 特定的类型(multi-key、TTL、unique)、读写 trade-off 以及使用 explain() 验证 — 是高性能 MongoDB 应用程序的必要的、高价值的知识,也是最重要的 MongoDB 主题之一,与 SQL databases 中索引的重要性相当。