如何为复杂的 MongoDB 查询创建索引

How to create an index for a complex MongoDB query

我需要为以下查询创建索引:

await Activity.find({
   $and: [
      {
         lastUpdated: {
            $gte: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
         },
      },
      {
         "followers._user": _user,
      },
      {
         global: true,
      }
   ]
})
.collation({
   locale: "en_US",
   numericOrdering: true,
})
.sort({
   lastUpdated: -1
})
.skip(
   length
)
.limit(
   10
)

我目前有以下索引,但查询没有使用它。

ActivitiesSchema.index(
  { "followers._user": 1, global: 1, lastUpdated: -1 },
  {
    collation: {
      locale: "en_US",
      numericOrdering: true,
    },
  }
);

我可以尝试解决这个问题吗?

将索引更改为:

{ lastUpdated: -1, "followers._user": 1, global: 1 }

注意: 它可能会影响依赖现有索引的其他查询

https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-index-prefix 读作:

If the sort keys correspond to the index keys or an index prefix, MongoDB can use the index to sort the query results. A prefix of a compound index is a subset that consists of one or more keys at the start of the index key pattern.

由于您按“lastUpdated”排序,索引应从它开始。

注意2:有了这个变化Mongodb 可以使用,但不能保证。还有许多其他因素,例如选择性和基数,例如global: true, 意味着从该字段的索引中获益的基数极低。另一方面,如果用户关注的不多并且总 activity 很大,则按“followers._user”索引进行过滤并进行内存排序可能会更便宜。由查询规划器决定使用哪个索引。