问题描述
我可能遗漏了一些东西,因为我还在学习插件和outs of MongoDB,但我需要帮助来分页集合.
I'm probably missing something since I'm still learning the ins andouts of MongoDB, but I need help with paging a collection.
我有一个包含名称列表的集合.
I have a collection that has a list of names.
底部圆形牛肉
鸡胸肉 6oz
鸡胸肉 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 missedthe 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
假设您有这些值:
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 &max 或创建复合索引.你可以只使用 $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 中使用范围查询进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!