Range based paging mongodb

前端 未结 1 1478
醉话见心
醉话见心 2020-12-13 16:07

on the mongodb docs it says: (source)

Unfortunately skip can be (very) costly and requires the server to walk from the beginning of the collection,

相关标签:
1条回答
  • 2020-12-13 16:44

    The basic idea is to write the paging into the query predicate pattern.

    For example if you list forum posts by date and you want to show the next page then use the date of the last post on the current page as a predicate. MongoDB can use the index built on the date field.

    //older posts
    db.forum_posts.find({date: {$lt: ..last_post_date..} }).sort({date: -1}).limit(20);
    

    Of course this gets a little more complicated if the field you are using for sorting is not unique.

    0 讨论(0)
提交回复
热议问题