MongoDB-索引
在MongoDB中,索引(index)是用于提高查询性能的数据结构。通过创建索引,mongo可以快速定位和访问数据,避免全表扫描
索引类型
索引 | 定义 | 示例 |
---|---|---|
单字段索引 | 在单个字段上创建的索引 | db.collection.createIndex({ field: 1 }); // 1 表示升序,-1 表示降序 |
复合索引 | 在多个字段上创建的索引 | db.collection.createIndex({ field1: 1, field2: -1 }); |
多键索引 | 在数组字段上创建的索引 | db.collection.createIndex({ arrayField: 1 }); |
全文索引 | 用于支持全文搜索的索引 | db.collection.createIndex({ field: “text” }); |
地理空间索引 | 用于支持地理空间查询的索引 | db.collection.createIndex({ location: “2dsphere” });//2dsphere支持球面几何查询,2d支持平面几何查询 |
哈希索引 | 使用哈希函数对字段值进行索引 | db.collection.createIndex({ field: “hashed” }); |
唯一索引 | 确保索引字段的值唯一 | db.collection.createIndex({ field: 1 }, { unique: true }); |
稀疏索引 | 仅对包含索引字段的文档创建索引 | db.collection.createIndex({ field: 1 }, { sparse: true }); |
TTL索引 | 用于自动删除过期文档的索引 | db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); |
创建和管理
功能 | 示例 |
---|---|
创建索引 | db.collection.createIndex({ field: 1 }); |
查看索引 | db.collection.getIndexes(); |
删除索引 | db.collection.dropIndex(“field_1”); |
重建索引 | db.collection.reIndex(); |
使用
-
查询优化:mongo的查询优化器会自动选择最合适的索引。可以使用explain()分析查询计划
db.collection.find({ field: "value" }).explain("executionStats");
-
索引覆盖:如果查询仅使用索引字段,mongo可以直接从索引中返回结果,无需访问文档
db.collection.createIndex({ field1: 1, field2: 1 }); db.collection.find({ field1: "value" }, { field2: 1, _id: 0 });
-
指定索引:可以使用hint()来强制mongo使用一个索引
db.collection.createIndex({ field1: 1, field2: 1 }); db.collection.createIndex({ field1: 1}).hint({ field1: 1, field2: 1 });