首页 > 解决方案 > GraphQL MongoDB:实现基于光标的 $text $search 分页

问题描述

在普通的光标分页中,我会根据created字段对文档进行过滤和排序,这非常简单。像这样:

// `cursor` is a string
const books = await this.BooksModel.find({
    ...(cursor ? { created: { $lt: new Date(cursor) } } : null),
})
    .sort({ created: -1 })
    .limit(first)

同时,在实现搜索时,我(我想我)必须根据textScore可能有重复的元数据对文档进行排序和过滤。为了防止这种情况,我需要另一个字段来过滤,即_id. 我想它会是这样的:

// `cursor` is { id: string, score: number }
const books = await this.BooksModel.aggregate(
    [
        { $match: { _id: { $ne: ObjectId(cursor.id) }, $text: { $search: 'sed' } } },
        { $project: { title: 1, score: { $meta: 'textScore' } } },
        { $match: { score: { $lt: cursor.score } } }
    ]
)

为了实现上面的示例,我需要光标不仅包含文档_id(如普通分页),还包含score. 我想光标的长度(解码)与正常的相比会很长。此外,光标现在包含一个对象而不仅仅是字符串,这对于像我这样的菜鸟来说是很奇怪的。这真的是构建基于光标的搜索分页的方法吗?

标签: mongodbpaginationgraphqldatabase-cursor

解决方案


推荐阅读