问题描述
如果这是我的收藏结构:
If this is my collection structure:
{ "_id": ObjectId("4fdbaf608b446b0477000142"),
"name": "product 1",
},
{ "_id": ObjectId("fghfghfgjhjghkgk"),
"name": "product 2",
},
{ "_id": ObjectId("fghfghfgjhjghkgk"),
"name": "product 3",
}
我查询产品1,是否可以查询下一个文档,在这种情况下为产品2?
and I query product 1, is there a way to query the next document, which in this case would be product 2?
推荐答案
如果想要可预测的结果顺序,最好添加明确的sort()
标准.
It is best to add explicit sort()
criteria if you want a predictable order of results.
假设您遵循的顺序是插入顺序",并且您使用的是MongoDB的默认生成的ObjectId,那么您可以基于ObjectId进行查询:
Assuming the order you are after is "insertion order" and you are using MongoDB's default generated ObjectIds, then you can query based on the ObjectId:
// Find next product created
db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142") }}).limit(1)
请注意,此示例之所以有效,是因为:
Note that this example only works because:
- ObjectId的前四个字节是根据unix样式的时间戳计算的(请参阅: ObjectId规格)
- 仅对
_id
的查询将使用默认的_id
索引(按ID排序)来查找匹配项
- the first four bytes of the ObjectId are calculated from a unix-style timestamp (see: ObjectId Specification)
- a query on
_id
alone will use the default_id
index (sorted by id) to find a match
实际上,这种隐式排序与:
So really, this implicit sort is the same as:
db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142" )}}).sort({_id:1}).limit(1);
如果您在查询中添加了更多条件以限定如何查找下一个"产品(例如,category
),则查询可能使用其他索引,并且顺序可能与您期望的不一样.
If you added more criteria to the query to qualify how to find the "next" product (for example, a category
), the query could use a different index and the order may not be as you expect.
您可以通过 explain()检查索引的使用情况.
You can check index usage with explain().
这篇关于在MongoDb中查找下一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!