且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

即使在索引字段上,MongoDB排序也非常慢

更新时间:2021-08-20 22:28:03

你应该运行解释反对你的查询,它将帮助你弄清楚发生了什么。

You should run explain against your query, it will help you figure out what's going on.

Mongo可能没有使用索引过滤和排序。当您使用 $或时,它可以使用多个索引来匹配选项。但是当你添加 sort 时,它可能会使它不能使用可用于过滤的索引。

It's likely that Mongo isn't using an index for both filtering and sorting. When you use an $or, it can use multiple indexes to match the options. But when you add a sort it may make it not use indexes available for filtering.

当你想要排序时在查询中,您需要确保已排序的字段位于您要命中的索引中(最后一个,或者它不能用它来排序)。

When you want to sort on a query, you need to make sure the sorted field is in the index you want to hit (last, or it can't use it to sort).

你或许可以通过传递索引提示加快速度。我不知道您的查询匹配了多少个文档,但是如果它是一个小数字并且您确保初始条件是命中索引,那么 _id 上的排序可以完成很快。

You may be able to speed it up by passing an index hint, too. I don't know how many docs your query matches, but if it's a small number and you make sure the initial conditions are hitting an index, the sort on _id can be done quickly.