1. 诊断查询模式,明确优化方向
使用explain()方法分析查询执行计划,是索引优化的基础。通过db.collection.find(query).explain("executionStats")可查看查询是否使用了索引、索引使用效果(如winningPlan中的indexName)及性能指标(如executionTimeMillis)。重点关注stage字段(若为COLLSCAN则表示全表扫描,需优化),以及usedIndexes列表确认索引命中情况。
2. 精准创建高效索引
db.users.createIndex({username: 1})(1表示升序,-1表示降序)。适用于精确匹配或范围查询。db.users.createIndex({username: 1, age: -1}))。若查询条件为{username: "Alice", age: {$gt: 20}},此索引可高效命中;若查询仅含{age: {$gt: 20}},则索引无效。db.users.createIndex({username: 1, email: 1}),查询{username: "Alice"}可直接从索引返回结果,无需访问数据文件)。3. 删除冗余与无用索引
db.collection.getIndexes()列出集合所有索引,识别重复(如同一字段的多组索引)或未使用的索引。db.collection.dropIndex({field: 1})删除不再需要的索引(如业务变更后不再查询的字段索引),减少写操作的开销(每写一次数据需更新所有相关索引)。4. 强制使用与定期重建索引
explain()显示查询未使用最优索引,可使用hint()强制指定索引(如db.users.find({username: "Alice"}).hint({username: 1}))。需谨慎使用,避免人为干预导致性能下降。db.collection.reIndex()重建索引,优化碎片化(建议在低峰期执行,避免影响线上业务)。5. 监控索引使用情况
db.setProfilingLevel(2)开启慢查询日志(记录所有查询),或db.setProfilingLevel(1, {slowms: 100})记录超过100ms的查询。使用db.system.profile.find()查看慢查询详情,定位未使用索引的查询。6. 硬件与配置优化
storage.wiredTiger.engineConfig.cacheSizeGB设置为物理内存的50%-70%(如16GB内存可设置8GB),提升索引命中率。storage.dbPath)部署在SSD上。/etc/mongod.conf中的net.maxIncomingConnections(连接池大小,默认100,可根据并发量调整)、operationProfiling.mode(慢查询监控模式)等参数,提升索引维护效率。7. 分片与复制集扩展
_id作为分片键)。rs.add("secondary_host:27017")添加从节点)。