为什么 MongoDB skip() 不使用索引?

Why MongoDB skip() doesn't use indexes?

MongoDB 的文档中指出,使用带大偏移量的 skip() 很慢。

The skip() method requires the server to scan from the beginning of the input results set before beginning to return results. As the offset increases, skip() will become slower.

假设我们排序所依据的字段上有一个索引,为什么 MongoDB 不能直接“跳”到正确的位置?例如如果我们有一个排序数组,我们可以在 O(1) 中得到第 100 个项目。为什么数据库不能做同样的事情?

据我所知,OFFSET/LIMIT 在 SQL 数据库中发生了完全相同的事情,因此我将非常感谢涵盖这两种情况的答案。

索引不作为数组存储在 disk/in 内存中。它们存储为树,有点像链表。

因此,不可能像您所说的那样“跳”到正确的位置。

请注意,文档并未说明服务器迭代 文档 ,而是迭代 结果集 。理论上,这可以通过索引扫描来完成。