按查詢需求選類型
user_id
)。content
字段)。2dsphere
索引)。覆蓋索引優化
確保查詢字段全部包含在索引中,避免回表查詢(如db.collection.find({字段}, {字段:1, _id:0})
)。
定期審查索引
db.collection.getIndexes()
查看索引列表,刪除未使用的冗余索引。db.collection.explain("executionStats")
分析查詢計劃,定位低效索引。索引重建與優化
db.collection.reIndex({background:true})
后臺重建索引,避免阻塞。{createdAt:1}, {expireAfterSeconds:3600}
)。提升硬件性能
分片與副本集
查詢優化
{name:1, age:1, _id:0}
)。skip
深度分頁,改用游標分頁或范圍查詢。寫入優化
insertMany
),減少網絡開銷。db.collection.dropIndex()
)后批量寫入,再重新創建索引。mongostat
、mongotop
或MongoDB Atlas監控慢查詢,針對性優化。slowms
參數),定期分析異常查詢。參考來源: