Mongodb 查询优化

2020-05-11 10:52:37 浏览数 (1)

A good writeup of how your index should be created is available in Optimizing MongoDB Compound Indexes. Let's take the main point of the article, where the compound index ordering should be equality --> sort --> range:

Your query "shape" is:

代码语言:javascript复制
db.collection.find({category:..., _id: {$gt:...}})
             .sort({sticky:-1, lastPostAt:-1, _id:1})
             .limit(25)

We see that:

  • category:... is equality
  • sticky:-1, lastPostAt:-1, _id:1 is sort
  • _id: {$gt:...} is range

So the compound index you need is:

代码语言:javascript复制
{category:1, sticky:-1, lastPostAt:-1, _id:1}

0 人点赞