我可能错过了什么,因为我还在学习ins和

我有一个Collection ,里面有一系列的名字.

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"上创建了一个复合索引.

我运行以下查询:

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

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

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

如果我在寻呼,从顶部开始.这个问题可能会漏掉

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盎司的鸡胸肉,从那里开始.

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

推荐答案

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

Create Compound Index

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

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}

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

1st Page

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

2nd Page

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

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

3rd Page

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

以下是$min/max的文档:

如果集合中没有重复的值,则不需要使用min&;或者创建一个复合索引.您只需使用$lt&$gt.

Mongodb相关问答推荐

为什么 mongoose 在 mongodb 中找不到我的数据

DB.collection('comments').find() 不工作

使用 $addFields 将字段添加到 $lookup 结果中的每个项目

在 MongoDB 中,如何使用对当前值进行操作的函数来更新嵌套文档的值?

根据状态过滤 mongoDb 中的结果

如何在mongodb中级联删除文档?

mongoose中的 required是什么意思?

MongoDB 使用自定义表达式或函数进行排序

MongoDB:按标签获取文档

Mongoose 与 mongodb 如何返回刚刚保存的对象?

mongod 和 mongo 命令在 Windows 10 上不起作用

MongoDB中超过2GB的数据库

mongoose得到`TypeError: user.save is not a function` - 出了什么问题

Mongo聚合框架,排序然后分组不起作用

如何防止MongoDB在查找文档时返回对象ID?

RoboMongo:不显示所有文档

Mongoose Select 要从 findOneAndUpdate 返回的字段

spring 数据MongoDB.生成id的错误

我可以使用字符串作为 mongodb 文档的 ID 类型吗?

带有条件的MongoDB聚合查找