Check out a free preview of the full Introduction to MongoDB course
The "Pagination" Lesson is part of the full, Introduction to MongoDB course featured in this preview video. Here's what you'd learn in this lesson:
Scott introduces cursor based pagination and skip limit based pagination. An example of how to implement skip limit pagination is demonstrated.
Transcript from the "Pagination" Lesson
[00:00:00]
>> Scott Moss: Pagination, okay, so there's many ways to do pagination in databases in general. The two approaches that I like to use the best is either a cursor based pagination or a skip limit based pagination. A cursor based pagination is basically, you send back, let's say a list of 100 results.
[00:00:26]
The last result in item is basically the cursor, it's where you left off, so when you send the request back to the next one, you start from that cursor. So some people use the indexes as the cursor, some people make their own cursor. So they'll send back all the items, they'll actually make a cursor, and a cursor is just an ID that points to something.
[00:00:44]
Something unique that you save, this is like a bookmark in your book. It's like, here's where I left off, and it can be anything. Something that you know is guaranteed to allow you to figure out where you left off. An item in the results is the best thing as a cursor, because if you sort your results and you get the last thing in the result, you're guaranteed to start off where you left off there.
[00:01:02]
If everything is sorted, which it should be in pagination. So that's why people use the last item in the array for a cursor. So that's one way. The other way is just to skip a limit. So if you were gonna do that in Mongo, skip a limit, guess what?
[00:01:16]
They have a .skip and a .limit. So you can do pagination there. So if you were on page ten and there's ten things on a page, I'm sorry, if you were on page two and there was ten things on the page, you want to skip the first ten and you want to limit ten, so yeah, pagination.
[00:01:35]
So that would give you the second page of ten. Yeah, super simple. If you want to do cursor based, then that's a implementation detail. Are you saving the cursor in the database somewhere, are you using the last value? Whatever you're doing you have to grab it from the request object.
[00:01:50]
And you're gonna have to, find me the thing that I left off here. So you will do that, but with skipping limit, yeah, you're pretty good, but don't forget, you also have to do a sort. So you need to sort, otherwise you will get random results. So you wanna sort by something.
[00:02:05]
So whatever your sort field is, sort by that, and then do your skipping limit, and then that's pagination.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops