简体   繁体   中英

Pagination with MongoDB in Node.js (With Sorting)

Using suggestions from here and here , I'm trying to implement a scalable, paginating, stateless REST API in the following way:

//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 = ...

It works in most cases, but the problem is I have to sort a list of videos according to view count and then try to paginate.

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

This does not work since there might be multiple items with same view count and some items will miss out when we do 'viewCount'< last_view_count

Any ideas on how to solve this problem would be appreciated :)

You can sort and filter on a combination of fields that together uniquely identify documents. For example, sort on {viewcount: 'descending', _id: 'ascending'} , and filter on {viewcount <= last_view_count, _id > last_id} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM