MongoDB远程分页 [英] MongoDB ranged pagination

查看:48
本文介绍了MongoDB远程分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It's said that using skip() for pagination in MongoDB collection with many records is slow and not recommended.

可以使用远程分页(基于> _id比较)

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

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

这对于显示上一个很有用. &下一个按钮-但是要显示实际的页码1 ... 5 6 7 ... 124时,实现起来并不容易-您需要预先计算每个页面从哪个"_id"开始.

It's good for displaying prev. & next buttons - but it's not very easy to implement when you want to display actual page numbers 1 ... 5 6 7 ... 124 - you need to pre-calculate from which "_id" each page starts.

所以我有两个问题:

1)我什么时候应该开始担心呢?当太多记录"中skip()的运行速度明显变慢时?一千? 1000万?

1) When should I start worry about that? When there're "too many records" with noticeable slowdown for skip()? 1 000? 1 000 000?

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

2) What is the best approach to show links with actual page numbers when using ranged pagination?

推荐答案

好问题!

多少太多?" -当然,这取决于您的数据大小和性能要求.当我跳过500-1000条以上的记录时,我个人感到不舒服.

"How many is too many?" - that, of course, depends on your data size and performance requirements. I, personally, feel uncomfortable when I skip more than 500-1000 records.

实际答案取决于您的要求.这就是现代网站的功能(或至少其中一些功能).

The actual answer depends on your requirements. Here's what modern sites do (or, at least, some of them).

首先,导航栏如下所示:

First, navbar looks like this:

1 2 3 ... 457

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

They get final page number from total record count and page size. Let's jump to page 3. That will involve some skipping from the first record. When results arrive, you know id of first record on page 3.

1 2 3 4 5 ... 457

让我们跳过更多内容,然后转到第5页.

Let's skip some more and go to page 5.

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

您明白了.在每个点上,您都可以看到第一页,最后一页和当前页面,以及从当前页面向前和向后两个页面.

You get the idea. At each point you see first, last and current pages, and also two pages forward and backward from the current page.

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远程分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆