使用MongoDB分页 [英] Pagination with MongoDB

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

问题描述

我一直在使用MongoDB和RoR来存储日志数据.我正在提取数据,并希望分页结果.有没有人与MongoDB进行过分页,或者是否有在线资源可以帮助我入门?

I have been using MongoDB and RoR to store logging data. I am pulling out the data and looking to page the results. Has anyone done paging with MongoDB or know of any resources online that might help get me started?

欢呼

Eef

推荐答案

可以使用limit()skip()的组合来完成MongoDB中的分页.

Pagination in MongoDB can be accomplished by using a combination of limit() and skip().

例如,假设我们在活动数据库中有一个名为用户"的集合.

For example, assume we have a collection called users in our active database.

>> db.users.find().limit(3)

这将为我们检索前三个用户文档的列表.注意,这基本上与编写相同:

This retrieves a list of the first three user documents for us. Note, this is essentially the same as writing:

>> db.users.find().skip(0).limit(3)

对于接下来的三个,我们可以这样做:

For the next three, we can do this:

>> db.users.find().skip(3).limit(3)

这将跳过前三个用户记录,并为我们提供下三个记录.如果您的数据库中只有一个用户,请不要担心. MongoDB足够聪明,只返回存在的数据,不会崩溃.

This skips over the first three user records, and gives us the next three. If there is only one more user in your database, don't worry; MongoDB is smart enough to only return data that is present, and won't crash.

可以这样概括,大致相当于您在Web应用程序中所做的事情.假设我们有一个变量PAGE_SIZE设置为3,还有一个任意的PAGE_NUMBER:

This can be generalised like so, and would be roughly equivalent to what you would do in a web application. Assuming we have variables called PAGE_SIZE which is set to 3, and an arbitrary PAGE_NUMBER:

>> db.users.find().skip(PAGE_SIZE * (PAGE_NUMBER - 1)).limit(PAGE_SIZE)

关于如何在Ruby on Rails中使用此方法,我不能直接说,但是我怀疑Ruby MongoDB库公开了这些方法.

I cannot speak directly as to how to employ this method in Ruby on Rails, but I suspect the Ruby MongoDB library exposes these methods.

这篇关于使用MongoDB分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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