如何在Mongodb中实现分页? [英] How to implement paging in Mongodb?

查看:243
本文介绍了如何在Mongodb中实现分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对文章集合进行分页(按日期排序-别无其他).在Mongodb中做这样的事情的标准方式是什么?

I need to paginate a collection of articles (order by date - and nothing else). What is the standard way doing something like this in Mongodb?

由于性能问题,我将不使用skip()方法.我也不打算使用$ push方法.我所看到的最接近的方法是范围查询方法.但是,如果删除任何已排序的项目,则似乎失败.

I am not going to use the skip() method because of performance issues. Neither do I plan to use the $push method. The closest method I have seen is the range query method. But it seems to fail if any of the sorted items are removed.

推荐答案

范围排序应该很适合您.首次请求将采用按日期排序的前10个项目:

Range sorting should work well for you. First request will take first 10 items sorted by date:

db.articles.find({}).sort( { date : -1 } ).limit(10);

此后,您将需要存储上一个项目的某个日期,并在下一个分页请求中使用ID:

After this you will need store somewhere date of last item and use id in next paging request:

db.articles.find({"date": {$lt: storedDateOfLastItem}}).sort( { date : -1 } ).limit(10);

所以,我想它应该对您来说很好.要估算页面总数,您将需要使用.

So, i guess it should work well for you. To estimate total count of pages you will need to use count.

但是,如果删除任何已排序的项目,这似乎会失败.

But it seems to fail if any of the sorted items are removed.

例如,如果您要从第1页中删除文章,则可以肯定的是,由于存储的最后日期,第2页中断.为避免这种情况,您可以估算当前保存日期之前的项目数

If you will remove for example article from page #1 it for sure break page #2 because of stored last date will be changed. To avoid this you can estimate count of items that was before current saved date

db.articles.find({"date": {$gt: storedDateOfLastItem}}).sort( { date : -1 } ).count()

如果此计数发生更改(例如,删除了2条).您需要更新storedDateOfLastItem

If this count was changed (let say 2 articled was removed). You need to updated storedDateOfLastItem

db.articles.find({"date": {$gt: storedDateOfLastItem}}).sort( { date : -1 } ).take(2)

再次从上述请求的最后一个项目中获取storedDateOfLastItem,然后继续进行分页.

Again taking storedDateOfLastItem from last item of above request and continue make paging.

但是,我认为保留此分页是没有任何额外逻辑的,因为我认为删除文章是很少的操作.

But my opinion just keep this paging as it is without extra logic, because i suppose that article deletion is rare operation.

来自mongodb文档:

From mongodb documentation:

分页费用不幸的是,跳过可能会(非常)昂贵,并且需要 服务器从集合(或索引)的开头走走以获取 到偏移/跳过位置,然后才能开始返回页面 数据(限制).随着页码的增加,跳过的速度会变慢,并且 cpu占用更多资源,并且可能与IO绑定,并且具有更大的集合.

Paging Costs Unfortunately skip can be (very) costly and requires the server to walk from the beginning of the collection, or index, to get to the offset/skip position before it can start returning the page of data (limit). As the page number increases skip will become slower and more cpu intensive, and possibly IO bound, with larger collections.

基于范围的分页可更好地使用索引,但不允许 您可以轻松跳转到特定页面.

Range based paging provides better use of indexes but does not allow you to easily jump to a specific page.

这篇关于如何在Mongodb中实现分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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