首页 > 解决方案 > 应如何索引此查询以提高性能

问题描述

我有一个 MongoDB 查询

Schema: Demo
{
  a: String,
  b: Number,
  c: Bool,
  d: Number
}

Query:
db.Demo.find({ a:'test', c: true }).sort({b:-1, d: -1}).limit(40).explain("executionStats")

我试过应用这些索引:

类型 1 索引

  1. db.Demo.createIndex({b-1, d:-1})
  2. db.Demo.createIndex({a:1})
  3. db.Demo.createIndex({c:1})

类型 2 索引

  1. db.Demo.createIndex({a:1, c:1, b:-1, d:-1})

MongoDB 总是忽略TYPE 2 index作为被拒绝的计划并使用TYPE 1 Index. 但是 TYPE One 需要更多的时间,我认为它可以更优化。

按类型 1 查询解释结果。

....
"executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 20,
        "executionTimeMillis" : 351,
        "totalKeysExamined" : 647,
        "totalDocsExamined" : 647,
} 

标签: mongodbmongoosemongodb-querymongodb-indexes

解决方案


找到查询的完美索引:

这已在此博客中解释

优化 MongoDB 复合索引

查询将是 db.Demo.createIndex({c:1, b:-1, d:-1, a:1})


推荐阅读