如何在MongoDB中使用范围查询进行分页? [英] How to do pagination using range queries in MongoDB?

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

问题描述

由于我仍在学习ins和 脱离MongoDB,但我在分页集合方面需要帮助.

I'm probably missing something since I'm still learning the ins and outs of MongoDB, but I need help with paging a collection.

我有一个包含名称列表的集合.

I have a collection that has a list of names.

牛肉底圆
鸡胸肉6盎司
鸡胸肉8oz
鸡胸肉8oz
鸡胸肉8oz
鸡胸肉随机
鸡腿
鸡里脊肉
鸡大腿
粗盐

Bottom Round of Beef
Chicken Breast 6oz
Chicken Breast 8oz
Chicken Breast 8oz
Chicken Breast 8oz
Chicken Breast Random
Chicken Legs
Chicken Tenderloin
Chicken Thighs
Kosher Salt

我在"ProductName,_id"上创建了复合索引.

I created a compound index on "ProductName,_id".

我运行以下查询:

db.ProductGuideItem.find( { ProductName: { $gt: "Chicken Breast 8oz" } } ).sort({ProductName:1,_id:1}).limit(3); 

注意,这里有3个鸡胸肉8盎司"项目.

Notice there are 3 "Chicken Breast 8oz" items.

如果我运行该查询,我会得到...
鸡胸肉随机
鸡腿
鸡里脊肉

If I run that query I get...
Chicken Breast Random
Chicken Legs
Chicken Tenderloin

如果我正在分页并从顶部开始.该查询将丢失 其他2个鸡胸肉8盎司".

If I was paging and started from the top. The query would have missed the other 2 "Chicken Breast 8oz".

因此,如果每个页面只能包含3个项目,并且我想查看第2页,那么我应该看到..
鸡胸肉8oz
鸡胸肉8oz
鸡胸肉随机.

So if each page can only have 3 items and I want to see page 2 then I should see..
Chicken Breast 8oz
Chicken Breast 8oz
Chicken Breast Random.

但是我不是.它要到达最后的8盎司鸡胸肉,然后从那里开始.

But I'm not. It's going to the last Chicken Breast 8oz and starting from there instead.

有没有办法解决这个问题?
另外,如果列表以相反的方式排序,我该怎么办?

Is there a way around this?
Also how would I do this if the list was sorted the opposite way?

推荐答案

由于我正在分页的集合具有重复的值,因此我必须在ProductName和id上创建复合索引.

Since the collection I was paging had duplicate values I had to create a compound index on ProductName and id.

创建复合索引

db.ProductGuideItem.ensureIndex({ ProductName:1, _id:1});

这解决了我的问题.
参考: https://groups.google.com/d/msg/mongodb-user/3EZZIRJzW_A/oYH79npKZHkJ

This solved my problem.
Reference: https://groups.google.com/d/msg/mongodb-user/3EZZIRJzW_A/oYH79npKZHkJ

假设您具有以下值:

Assuming you have these values:

{a:1, b:1}
{a:2, b:1}
{a:2, b:2}
{a:2, b:3}
{a:3, b:1}

因此,您可以对基于范围的分页(页面大小为2)执行此操作:

So you do this for the range based pagination (page size of 2):

第一页

find().sort({a:1, b:1}).limit(2)
{a:1, b:1}
{a:2, b:1}

第二页

find().min({a:2, b:1}).sort({a:1, b:1}).skip(1).limit(2)

{a:2, b:2}
{a:2, b:3}

第三页

find().min({a:2, b:3}).sort({a:1, b:1}).skip(1).limit(2)
{a:3, b:1}

以下是$ min/max的文档: http://www.mongodb.org/display/DOCS/min+and+max+查询+说明符

Here are the docs for $min/max: http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

如果您的集合中没有重复的值,则无需使用min&最大值或创建复合索引.您可以只使用$ lt& $ gt.

If you don't have duplicate values in your collection, you don't need to use min & max or create a compound index. You can just use $lt & $gt.

这篇关于如何在MongoDB中使用范围查询进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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