[英]Pagination with MongoDB in Node.js (With Sorting)
使用来自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}
上进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.