1. 連接到MongoDB實例
在CentOS服務器上,使用mongo命令連接到本地MongoDB實例(若為遠程實例,需替換為對應IP和端口):
mongo
連接成功后,切換至目標數據庫(如myDatabase):
use myDatabase
2. 分析查詢模式(定位需索引字段)
使用explain()方法分析慢查詢的執行計劃,重點關注executionStats中的totalDocsExamined(掃描文檔數)、keysExamined(掃描索引鍵數)和winningPlan(執行的索引策略)。例如,分析users集合中username字段的查詢:
db.users.find({ username: "Alice" }).explain("executionStats")
若totalDocsExamined遠大于nReturned(返回文檔數),說明需為username字段創建索引。
3. 創建合適的索引
username):db.users.createIndex({ username: 1 }) // 1表示升序,-1表示降序
username和email時:db.users.createIndex({ username: 1, email: 1 })
explain()確認totalDocsExamined: 0)。例如,若查詢只需username和status字段:db.users.createIndex({ username: 1, status: 1 }, { projection: { _id: 0, username: 1, status: 1 } })
status: "active"的用戶):db.users.createIndex({ username: 1 }, { partialFilterExpression: { status: "active" } })
4. 刪除冗余或無用索引
getIndexes()方法列出集合的所有索引(包括_id索引):db.users.getIndexes()
email索引),減少寫入開銷和存儲占用:db.users.dropIndex("username_1_email_1") // 索引名稱可通過getIndexes()獲取
5. 強制使用索引(謹慎使用)
若查詢優化器未選擇最優索引,可使用hint()方法強制指定索引(如強制使用username索引):
db.users.find({ username: "Alice" }).hint({ username: 1 })
注意:僅在確認優化器選擇錯誤時使用,避免人為干預導致性能下降。
6. 定期重建索引(優化碎片)
隨著數據增刪改,索引會產生碎片,導致查詢性能下降。使用reIndex()方法重建集合索引(需在低流量時段執行,避免影響業務):
db.users.reIndex()
對于整個數據庫,可使用repairDatabase()命令(需停機,且需足夠磁盤空間):
use admin
db.runCommand({ repairDatabase: 1 })
7. 監控索引使用情況
db.setProfilingLevel(2, { slowms: 100 }) // 2表示記錄所有操作,slowms表示慢查詢閾值
查看慢查詢日志:db.system.profile.find().sort({ ts: -1 }).limit(10)
8. 硬件與配置優化(輔助提升性能)
wiredTigerCacheSizeGB參數(默認為物理內存的50%)足夠大,以緩存索引和熱點數據(如設置為服務器內存的70%)。修改/etc/mongod.conf文件:storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8 # 根據服務器內存調整
重啟MongoDB生效:sudo systemctl restart mongod
/var/lib/mongo)部署在SSD上,提升I/O性能(比HDD快3-5倍)。注意事項
mongodump備份集合,避免誤操作導致數據丟失。