Mongodb 如何对此查询编制索引以提高性能

Mongodb 如何对此查询编制索引以提高性能,mongodb,mongoose,mongodb-query,mongodb-indexes,Mongodb,Mongoose,Mongodb Query,Mongodb Indexes,我有一个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索引 db.Demo.createIndex({b-1,d:-1}) db.Demo.createIndex

我有一个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索引

  • db.Demo.createIndex({b-1,d:-1})
  • db.Demo.createIndex({a:1})
  • db.Demo.createIndex({c:1})
  • 第2类指数

  • createIndex({a:1,c:1,b:-1,d:-1})
  • MongoDB始终忽略
    类型2索引
    作为拒绝的计划,并使用
    类型1索引
    。但是第一类需要更多的时间,我认为它可以更优化

    按类型1查询解释结果

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

    找到查询的完美索引:

    这已经在这个博客中解释过了

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

    因为c是bool类型,其基数非常低,所以我假设您不需要在复合索引中包含c。