Ubuntu中MongoDB索引优化策略
db.users.createIndex({ age: 1 })(1表示升序,-1表示降序)。适用于简单查询场景,能有效提升查询速度。{ age: 1, name: 1 },创建复合索引db.users.createIndex({ age: 1, name: 1 }),可避免扫描多个单字段索引。db.users.find({ age: 1 }, { name: 1, age: 1 }).explain("executionStats")中,若索引包含name和age,则executionStats.executionStages.inputStage.stage显示为IXSCAN,而非FETCH)。db.articles.createIndex({ tags: 1 }))、地理空间索引(用于地理位置查询,如db.places.createIndex({ location: "2dsphere" }))或文本索引(用于全文搜索,如db.articles.createIndex({ content: "text" }))。通过explain("executionStats")方法查看查询的执行细节,重点关注:
winningPlan.inputStage.stage是否为IXSCAN(表示使用了索引),若为COLLSCAN则表示全表扫描;executionStats.executionTimeMillis(查询耗时)、executionStats.totalDocsExamined(扫描文档数)、executionStats.totalKeysExamined(扫描索引键数);executionStats.nReturned(返回文档数),判断查询效率是否符合预期。db.collection.getIndexes()查看集合中的所有索引,确认是否存在冗余或未使用的索引。db.setProfilingLevel(2)记录所有查询,db.setProfilingLevel(1)记录慢查询,默认阈值为100ms),通过db.system.profile.find()分析慢查询的索引使用情况。db.serverStatus().metrics.query中的totalQueries(总查询数)和indexOnly(覆盖索引查询数)计算索引命中率,评估索引有效性。db.collection.reIndex()重建索引,解决索引碎片化问题(碎片化会导致查询性能下降),尤其适用于数据量大幅增长或频繁更新的集合。getIndexes()识别未使用的索引(如长期未被查询命中的索引),使用db.collection.dropIndex("index_name")删除,减少写操作开销(每个索引都会增加插入、更新、删除的时间)和存储空间占用。userid比status更具区分度)、过滤性强(常用于where子句)的字段放在复合索引前面。例如,若查询条件多为{ userid: 1, status: 1 },则复合索引应为{ userid: 1, status: 1 }。hint()方法强制指定索引,如db.users.find({ age: 1 }).hint({ age: 1 }),但需谨慎使用(避免覆盖所有查询场景)。storage.wiredTiger.engineConfig.cacheSizeGB),建议设置为可用内存的70%~80%,确保索引能缓存在内存中,减少磁盘I/O。