Search code examples
mongodbmongoosemongodb-querymongodb-indexes

How this query should be indexed to increase performance


I have a MongoDB query

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")

I have tried applying these index:

TYPE 1 INDEX

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

TYPE 2 INDEX

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

MongoDB always ignore TYPE 2 index as rejected plans and use TYPE 1 Index. But TYPE One is taking more time and I think it can be more optimized.

Explain Results by TYPE 1 QUERY.

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

Solution

  • Found the Perfect Index for the Query:

    This has been explained in this blog

    Optimizing MongoDB Compound Indexes

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