Ubuntu下MongoDB索引优化实用技巧
一 基础与通用原则
db.collection.createIndex({...}, {background: true})。二 索引类型与适用场景
| 索引类型 | 典型场景 | 示例 |
|---|---|---|
| 单字段索引 | 单条件精确查询 | db.users.createIndex({name: 1}) |
| 复合索引 | 多条件查询与排序组合 | db.users.createIndex({age: 1, name: -1}) |
| 唯一索引 | 字段值需唯一(如邮箱、用户名) | db.users.createIndex({email: 1}, {unique: true}) |
| 部分索引 | 只为满足特定条件的文档建索引,减小体积 | db.users.createIndex({name: 1}, {partialFilterExpression: {status: "active"}}) |
| 文本索引 | 全文检索 | db.articles.createIndex({content: "text"}) |
| 地理空间索引 | 地理位置查询(2dsphere 支持球面几何) | db.places.createIndex({location: "2dsphere"}) |
三 查询设计与索引利用
explain("executionStats") 检查是否走索引、是否发生 COLLSCAN,并关注 totalKeysExamined、totalDocsExamined、executionTimeMillis 等关键指标。skip/limit 的大偏移。hint() 指定更优索引,或通过 indexFilterSet 验证索引过滤器的效果。四 监控与维护
db.setProfilingLevel(1, {slowms: 100}) 记录超过阈值的操作;db.system.profile.find().sort({millis: -1}) 定位最慢语句。explain 做针对性优化。tail -f /var/log/mongodb/mongod.log 实时查看耗时命令;必要时执行 db.runCommand({logRotate: 1}) 轮转日志。db.collection.reIndex()(注意会占用资源与锁)。storage.wiredTiger.engineConfig.cacheSizeGB),避免频繁换页影响索引与查询性能。五 实用命令清单
db.users.createIndex({name: 1}, {background: true, name: "idx_name"})db.users.createIndex({age: 1, name: -1})db.users.createIndex({email: 1}, {unique: true})db.users.createIndex({name: 1}, {partialFilterExpression: {status: "active"}})db.articles.createIndex({content: "text"})db.places.createIndex({location: "2dsphere"})db.users.getIndexes()db.users.dropIndex("idx_name") 或 db.users.dropIndexes()(保留 _id 索引)db.users.find({name: "Alice"}).explain("executionStats")db.setProfilingLevel(1, 100); db.system.profile.find().sort({millis: -1})