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")添加從節點)。