num*_*407 5 pagination mongodb
当您基于单个唯一字段进行分页时,范围分页是简单的,但是在具有非唯一字段(可能一次有多个字段)的情况下,它是如何工作的(如果有的话)?
TL;DR:使用基于范围的分页对“高级搜索”类型查询进行分页和排序是否合理或可能?这意味着对用户选择的(可能是非唯一的)字段进行查询和排序。
例如,假设我想对文字游戏中玩过的文字文档的搜索进行分页。假设每个文档都有 ascore和 a word,我想让用户对这些字段进行过滤和排序。这两个领域都不是独一无二的。假设相关字段有一个排序索引。
从简单开始,假设用户想要查看所有得分为 10 的单词:
// page 1
db.words.find({score: 10}).limit(pp)
// page 2, all words with the score, ranged on a unique _id, easy enough!
db.words.find({score: 10, _id: {$gt: last_id}}).limit(pp)
Run Code Online (Sandbox Code Playgroud)
但如果用户想要获取所有得分低于 10 的单词怎么办?
// page 1
db.words.find({score: {$lt: 10}}).limit(pp)
// page 2, getting ugly...
db.words.find({
// OR because we need everything lt the last score, but also docs with
// the *same* score as the last score we haven't seen yet
$or: [
{score: last_score, _id: {$gt: last_id}},
{score: {$lt: last_score}
]
}).limit(pp)
Run Code Online (Sandbox Code Playgroud)
现在,如果用户想要分数小于 10 且字母值大于“FOO”的单词该怎么办?查询的复杂性迅速增加,这只是具有默认排序的搜索表单的一种变体。
// page 1
db.words.find({score: {$lt: 10}, word: {$gt: "FOO"}}).limit(pp)
// page 2, officially ugly.
db.words.find({
$or: [
// triple OR because now we need docs that have the *same* score but a
// higher word OR those have the *same* word but a lower score, plus
// the rest
{score: last_score, word: {$gt: last_word}, _id: {$gt: last_id}},
{word: last_word, score: {$lt: last_score}, _id: {$gt: last_id}},
{score: {$lt: last_score}, word: {$gt: last_word}}
]
}).limit(pp)
Run Code Online (Sandbox Code Playgroud)
我想为这种模式编写一个查询生成器是可行的,但它看起来非常混乱并且容易出错。我倾向于回退到跳过具有上限结果大小的分页,但如果可能的话,我想使用范围分页。我对这将如何运作的想法完全错误吗?有没有更好的办法?
到目前为止,由于没有可行的替代方案,我实际上只是使用基于跳跃的分页和有限的结果集,以保持跳跃的可管理性。就我的目的而言,这实际上已经足够了,因为没有真正需要搜索然后分页到数千个。
您可以通过对唯一字段进行排序并保存该字段的值作为最后的结果来获得范围分页。例如:
// first page
var page = db.words.find({
score:{$lt:10},
word:{$gt:"FOO"}
}).sort({"_id":1}).limit(pp);
// Get the _id from the last result
var page_results = page.toArray();
var last_id = page_results[page_results.length-1]._id;
// Use last_id to get your next page
var next_page = db.words.find({
score:{$lt:10},
word:{$gt:"FOO"},
_id:{$gt:last_id}
}).sort({"_id":1}).limit(pp);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1562 次 |
| 最近记录: |