以前的方法不能很好扩展其原因是skip() 命令。因此,本节的目标是实现分页不使用skip()命令。为此,我们将利用在存储数据中的自然顺序,比如时间戳或文档中存储的标识。
在这个例子中,我们将使用“_id”存储每个文档。“_id”是一个MongoDB 的ObjectID结构,即 12 字节结构包含了时间戳、机械加工、进程标识符、计数器等。总体思路如下 :
检索当前页中的最后一个文档 _id
在下一个页面检索文件大于此”_id”
//Page 1 db.users.find().limit(pageSize); //Find the id of the last document in this page last_id = ... //Page 2 users = db.users.find({'_id'> last_id}). limit(10); //Update the last id with the id of the last document in this page last_id = ...
这种方法利用内在的规则存在_id字段。也因为“_id”字段是默认的查找操作,它是非常好的性能指标。如果你使用的字段没有被索引,那么你在操作中会受到困扰,所以确保字段被索引是非常重要的。
同样,如果你希望数据按照特定顺序进行排序分页的话,那么你还可以使用sort()条款与上述技术。重要的是要确保排序过程是利用索引来获得最佳性能。您可以使用.explain()后缀来查询。
users = db.users.find({'_id'> last_id}). sort(..).limit(10); //Update the last id with the id of the last document in this page last_id = ...
以上就是MongoDB快速翻页的方法,希望能给大家一个参考,也希望大家多多支持。