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

Ranged pagination (based on >_id comparsion) could be used

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

它很适合显示prev&"下一步"按钮——但当你想显示实际的页码时,这并不容易实现...5 6 7 ... 124-您需要预先计算每页从哪个"_id"开始.

所以我有两个问题:

1) 我什么时候开始担心这个?当有"太多记录"且skip()速度明显减慢时?1 000? 1 000 000?

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

推荐答案

问得好!

"多少是太多了?"-当然,这取决于数据大小和性能要求.一、 就个人而言,当我跳过超过500-1000条记录时会感到不舒服.

实际答案取决于你的要求.以下是现代网站(或者至少是其中一些网站)的功能.

首先,导航栏看起来像这样:

1 2 3 ... 457

他们从总记录数和页面大小中得到最终的页码.让我们跳到第三页.这将涉及从第一条记录中略过一些内容.当结果到达时,您知道第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});

Mongodb相关问答推荐

防止查找简单字段

在MongoDB中,如何使用$in来匹配存储在数组变量中的值

从两个相连的文件中获取电话和邮箱的渠道是什么?

多键索引,性能问题

更新值导致错误 Golang MongoDB

嵌套数组 $unwind 和 $group 在 mongoDB 中重新组合在一起

在推入 mongodb 时自动填充 golang struct 中的 created_at 和 updated_at

在 MongoDB 中打开连接的 SocketTimeout

MongoDB聚合多条件

MongoDB C# 驱动程序 - 如何将 _id 存储为 ObjectId 但映射到字符串 Id 属性?

MongoDB 更改流副本集限制

如何使用python将csv数据推送到mongodb

MongoDB插入引发重复键错误

Springboot 使用 find*() 查询时出现 Mongodb 错误

mongo php副本连接非常慢

ExpressJS & Mongoose REST API struct :最佳实践?

MongoDB中超过2GB的数据库

MongoException: Index with name: code already exists with different options

缩短 MongoDB 属性名称值得吗?

Mongodb Compass 无法在 Ubuntu 18.10 中打开