MongoDB 范围分页 [英] MongoDB ranged pagination

查看:28
本文介绍了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 000 000?

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天全站免登陆