Skip to content

Instantly share code, notes, and snippets.

@Haleluak
Created February 18, 2020 04:00
Show Gist options
  • Select an option

  • Save Haleluak/f9fb8c86f4546d54b74af5b308fab8cd to your computer and use it in GitHub Desktop.

Select an option

Save Haleluak/f9fb8c86f4546d54b74af5b308fab8cd to your computer and use it in GitHub Desktop.

Revisions

  1. Haleluak created this gist Feb 18, 2020.
    17 changes: 17 additions & 0 deletions mongo
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    Using this property of ObjectId and also taking into consideration the fact that _id is always indexed, we can devise following approach for pagination:

    Fetch a page of documents from database
    Get the document id of the last document of the page
    Retrieve documents greater than that id
    In Mongo Shell your pagination code looks something like this

    // Page 1
    db.students.find().limit(10)

    // Page 2
    last_id = ... # logic to get last_id
    db.students.find({'_id': {'$gt': last_id}}).limit(10)

    // Page 3
    last_id = ... # logic to get last_id
    db.students.find({'_id': {'$gt': last_id}}).limit(10)