在CentOS上進行MongoDB索引優化,可按以下步驟操作:
分析查詢模式
使用db.collection.explain("executionStats")分析查詢計劃,查看索引使用情況。
創建合適索引
db.collection.createIndex({字段: 1/-1})。db.collection.createIndex({字段1: 1, 字段2: -1}),注意字段順序與查詢條件匹配。刪除冗余索引
通過db.collection.getIndexes()查看索引,刪除不再使用的索引。
維護索引性能
db.collection.reIndex()。mongostat、mongotop或第三方工具(如Prometheus)分析慢查詢。硬件與配置優化
/etc/mongod.conf中storage.wiredTiger.engineConfig.cacheSizeGB參數,合理分配內存。分片與高級優化(可選)
對于大規模數據,使用分片(sh.shardCollection())分散負載。
操作前建議先備份數據,并在測試環境驗證優化效果。