Ubuntu环境下MongoDB索引优化技巧
为经常用于查询条件的字段创建索引是提升查询性能的基础。例如,若经常根据userid字段查询,可执行db.transactions.createIndex({userid: 1})创建升序索引。需根据查询模式针对性创建,避免盲目添加索引。
db.collection.createIndex({field: 1}));db.collection.createIndex({field1: 1, field2: -1})),字段顺序需匹配查询条件;db.collection.createIndex({location: "2dsphere"}));db.collection.createIndex({content: "text"}))。通过explain()方法查看查询执行计划,判断索引是否被有效利用。例如,db.collection.find({query}).explain("executionStats")可返回keysExamined(扫描的索引键数量)、docsExamined(扫描的文档数量)等指标,若keysExamined远大于nreturned(返回的文档数量),则需优化索引。
{age: 1, name: 1}比{name: 1, age: 1}更适合查询age > 18);{a:1, b:1}和{b:1, a:1}只需保留一个;包含关系的索引(如{b:1, c:1}和{a:1, b:1, c:1})只需保留后者;{a:1, b:1, d:1, e:-1, c:1})。若查询的所有字段都包含在索引中,MongoDB可直接从索引返回结果,无需访问源文档(称为“覆盖查询”)。例如,查询{field1: value1, field2: value2}时,创建索引{field1:1, field2:1}并确保查询不返回_id(或将其加入索引)。可通过explain()的totalDocsExamined: 0判断是否为覆盖查询。
db.collection.reIndex()重建索引以减少碎片;db.collection.dropIndex("indexName")删除不再使用的索引,减少存储占用和写操作开销。在特殊场景下,可使用hint()强制MongoDB使用指定索引(如测试索引性能或优化复杂查询)。例如,db.collection.find({query}).hint({field:1})。
使用MongoDB自带工具(如mongostat查看索引操作统计、mongotop查看集合级别的索引使用情况)或第三方工具(如Percona Monitoring and Management (PMM))实时监控索引性能,及时发现性能瓶颈。