使用 MongoDB 进行分页 [英] Pagination with MongoDB

查看:34
本文介绍了使用 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?

干杯

伊夫

推荐答案

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

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

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

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