按查询需求选类型
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参数),定期分析异常查询。参考来源: