MongoDB Tutorial 0/120 lessons ~6 min read Lesson 39

    Pagination

    Pagination in MongoDB has two flavors: offset (skip + limit, simple but slow) and cursor-based (using the last item's id/timestamp, fast at any depth).

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Pagination in MongoDB has two flavors: offset (skip + limit, simple but slow) and cursor-based (using the last item's id/timestamp, fast at any depth). For real apps, always prefer cursor-based.

    Syntax reference

    js
    // Cursor-based ('seek')
    const next = await db.posts
    .find({ _id: { $lt: lastSeenId } })
    .sort({ _id: -1 })
    .limit(20)
    .toArray();

    Real-world use

    Instagram, Twitter, GitHub — all use cursor-based pagination for performance.

    Best practices

    • Cursor pagination for any feed-style UI.
    • Avoid skip() for offsets larger than a few hundred.
    Ready to mark this lesson complete?Track your journey across the entire course.