performance - MongoDB 范围分页

据说在有很多记录的MongoDB集合中使用skip()进行分页很慢,不推荐。

可以使用范围分页(基于>_id比较)

db.items.find({_id: {$gt: ObjectId('4f4a3ba2751e88780b000000')}});

它有利于显示上一页。 & 下一个按钮 - 但是当您想要显示实际页码 1 ... 5 6 7 ... 124 时实现起来并不容易 - 您需要预先计算每个页面从哪个“_id”开始。

所以我有两个问题:

1) 我应该什么时候开始担心这个问题?当有“太多记录”时,skip() 速度明显减慢? 1000? 1 000 000?

2) 使用范围分页时,用实际页码显示链接的最佳方法是什么?

最佳答案

好问题!

“多少才算太多?” - 当然,这取决于您的数据大小和性能要求。当我跳过超过 500-1000 条记录时,我个人会感到不舒服。

实际答案取决于您的要求。以下是现代网站的作用(或至少是其中一些)。

首先,导航栏是这样的:

1 2 3 ... 457

他们从总记录数和页面大小中获得最终页码。让我们跳到第 3 页。这将涉及从第一条记录中跳过一些内容。当结果到达时,您会知道第 3 页上第一条记录的 id。

1 2 3 4 5 ... 457

让我们跳过一些内容并转到第 5 页。

1 ... 3 4 5 6 7 ... 457

你明白了。在每一点上,您都会看到第一页、最后一页和当前页,以及从当前页向前和向后的两页。

查询

var current_id; // id of first record on current page.

// go to page current+N
db.collection.find({_id: {$gte: current_id}}).
              skip(N * page_size).
              limit(page_size).
              sort({_id: 1});

// go to page current-N
// note that due to the nature of skipping back,
// this query will get you records in reverse order 
// (last records on the page being first in the resultset)
// You should reverse them in the app.
db.collection.find({_id: {$lt: current_id}}).
              skip((N-1)*page_size).
              limit(page_size).
              sort({_id: -1});

https://stackoverflow.com/questions/9703319/

相关文章:

node.js - 如何在 Mongoose/Node.js 中同时保存多个文档?

javascript - 是否有 Mongoose 连接错误回调

mongodb - 如何使用 mongodump 转储的数据?

node.js - 在 Mongoose 中保存对象后如何获取 objectID?

mongodb - 显示我当前在 MongoDB 中使用的数据库的命令?

mongodb - 无法将 MongoDB 作为服务启动

user-interface - MongoDB的GUI工具

node.js - MongoDB 不工作。 "ERROR: dbpath (/data/db) d

python - PyMongo upsert 抛出 "upsert must be an inst

mongodb - MongoDB中 "id"和 "_id"字段的区别