gpt4 book ai didi

javascript - Node.js 中的 MongoDB 分页(带排序)

转载 作者:行者123 更新时间:2023-11-28 18:54:33 26 4
gpt4 key购买 nike

使用 here 的建议和 here ,我尝试通过以下方式实现可扩展、分页、无状态的 REST API:

//Page 1
db.users.find().limit(pageSize);
//Find the id of the last document in this page
last_id = ...

//Page 2
users = db.users.find({'_id'> last_id}).limit(pageSize);
//Update the last id with the id of the last document in this page
last_id = ...

它在大多数情况下都有效,但问题是我必须根据观看次数对视频列表进行排序,然后尝试分页。

// Page 2
videos = db.videos.find({'viewCount'< last_view_count}).sort({viewCount : 'descending'}).limit(pageSize);

这不起作用,因为可能有多个项目具有相同的观看次数,并且当我们执行 'viewCount'< last_view_count 时,某些项目会丢失。

任何有关如何解决此问题的想法将不胜感激:)

最佳答案

您可以对共同唯一标识文档的字段组合进行排序和过滤。例如,按 {viewcount: 'descending', _id: 'ascending'} 排序,并过滤 {viewcount <= last_view_count, _id > last_id} .

关于javascript - Node.js 中的 MongoDB 分页(带排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com