在CentOS上优化MongoDB索引可以显著提升数据库的性能。以下是一些关键步骤和策略:
explain()
方法分析查询计划,了解查询是否使用了索引,以及索引的使用效果。db.collection.createIndex({ field: 1 })
db.collection.createIndex({ field1: 1, field2: -1 })
db.collection.createIndex({ field1: 1, field2: 1 })
db.collection.createIndex({ field: 1 }, { unique: true })
db.collection.getIndexes()
查看当前索引。db.collection.dropIndex({ field: 1 })
hint()
方法强制MongoDB使用特定的索引。db.collection.find(query).hint({ field: 1 })
db.reIndex()
命令定期重建索引,以减少碎片化。db.collection.reIndex()
wiredTigerCacheSizeGB
、oplogSizeMB
等。db.users.createIndex({ username: 1 }) // 为 username 字段创建升序索引
db.users.createIndex({ username: 1, age: -1 }) // 为 username 和 age 字段创建复合索引
db.users.find({ username: "alice" }).hint({ username: 1 }) // 强制使用 username 字段的索引
db.users.dropIndex({ username: 1 }) // 删除 username 字段的索引
db.setProfilingLevel(2) // 启用慢查询日志
db.currentOp() // 查看当前操作
通过以上步骤,你可以有效地优化CentOS上MongoDB的索引策略,从而提高查询性能和整体系统效率。