mongodb 排序而不是_id,并使用mongod和nodeJ中的最后一个记录id进行分页

hyrbngr7  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(132)

我使用代码中提到的三个不同的过滤器对数据进行过滤。这是我的代码

/* Initialize pipeline */
        const pipeline = [];

        /* All reviews of Auth Host */
        pipeline.push({
            $match: { host_id: new ObjectId(host_id) },
        });

        /* High rated on top */
        if (filter && filter == "Highest Rated") {
            pipeline.push({
                $sort: {
                    rating: -1,
                    _id: -1,
                },
            });
        } else if (filter && filter == "Newest") {
            /* Newest on top */
            pipeline.push({
                $sort: {
                    _id: -1,
                },
            });
        } else if (filter && filter == "Oldest") {
            pipeline.push({
                $sort: {
                    _id: 1,
                },
            });
        }
/* Pagination */
        if (last_rec_id) {
            let query;
            if (filter !== "Highest Rated") {
                query = filter === "Oldest" || !filter ? { $gt: new ObjectId(last_rec_id) } : { $lt: new ObjectId(last_rec_id) };

                pipeline.push({
                    $match: {
                        _id: query,
                    },
                });
            } else {
                query = {
                    $or: [
                        { rating: { $lte: 5 } },
                        {
                            rating: 5,
                            _id: { $lt: new ObjectId(last_rec_id) }, // Secondary sorting by _id
                        },
                    ],
                };
                pipeline.push({
                    $match: query,
                });
            }
        }

所有过滤器都能很好地使用分页,但使用last_rec_id的分页不适用于filter=“Highest Rated”,我得到的记录很好,但当我应用分页时,它不会给出给予准确的结果,

g6ll5ycj

g6ll5ycj1#

而不是最后一个记录ID,我宁愿使用页码分页。

/* Initialize pipeline */
const pipeline = [];

/* All reviews of Auth Host */
pipeline.push({
    $match: { host_id: new ObjectId(host_id) },
});

/* High rated on top */
if (filter && filter == "Highest Rated") {
    pipeline.push({
        $sort: {
            rating: -1,
            _id: -1,
        },
    });
} else if (filter && filter == "Newest") {
    /* Newest on top */
    pipeline.push({
        $sort: {
            _id: -1,
        },
    });
} else if (filter && filter == "Oldest") {
    pipeline.push({
        $sort: {
            _id: 1,
        },
    });
}

/* Pagination Logic */
if (page) {
    const pageSize = 10; // Change this to your desired page size
    const skipAmount = (page - 1) * pageSize;

    pipeline.push({
        $skip: skipAmount,
    });
}

相关问题