MongoDB 在 Ubuntu 上的索引优化方法
一 索引类型与创建要点
db.collection.createIndex({ field: 1 });复合索引:db.collection.createIndex({ a: 1, b: -1 });唯一索引:db.collection.createIndex({ email: 1 }, { unique: true });文本索引:db.collection.createIndex({ title: "text", body: "text" });哈希索引:db.collection.createIndex({ userId: "hashed" })。db.collection.getIndexes();删除索引:db.collection.dropIndex("indexName") 或 db.collection.dropIndexes()。db.collection.createIndex({ field: 1 }, { background: true })。二 查询与索引设计原则
db.users.createIndex({ username: 1, status: 1, age: 1 }),查询只返回这些字段即可走覆盖索引。sort + skip/limit 分页,务必在排序列上建立索引,否则深分页性能急剧下降。$match 阶段使用索引减少后续处理的数据量。三 监控分析与维护
db.orders.find({ status: "A", total: { $gte: 100 } }).sort({ created_at: -1 }).explain("executionStats")。db.collection.stats() 可查看索引大小与使用情况,识别低效或冗余索引。四 Ubuntu 系统层面的优化配合
echo never > /sys/kernel/mm/transparent_hugepage/enabled,减少内存管理开销,提升数据库稳定性与性能。/etc/security/limits.d/mongodb.conf 提升 nofile/nproc,如 mongod soft/hard nofile 64000、mongod soft/hard nproc 64000,避免连接耗尽。/etc/mongod.conf 中合理设置 storage.wiredTiger.engineConfig.cacheSizeGB,通常将可用内存的 70%–80% 分配给 WiredTiger 缓存(结合实例总内存与系统需求)。五 实用索引策略清单
^term),优先使用 文本索引 或其他检索方案。