Fetch Records in batches by cursors

Hi @Rajeswari_Rathnavel - welcome to the community!

You can use skip() and limit() to achieve this.

For example, you could do something like…

let skipThisManyResults = 0;
let numberOfResultsToRetrieve = 5;

let cursor = client.db("Test").collection("things")
    .find({})
    .skip(skipThisManyResults)
    .limit(numberOfResultsToRetrieve);

while (skipThisManyResults < await cursor.count()) {

    while (await cursor.hasNext()) {
        console.log(await cursor.next());
    }

    skipThisManyResults += numberOfResultsToRetrieve;

    cursor = client.db("Test").collection("things")
        .find({})
        .skip(skipThisManyResults)
        .limit(numberOfResultsToRetrieve);
}

There are some drawbacks to this approach, which Justin explains in this blog post: Paging with the Bucket Pattern - Part 1 | MongoDB Blog

2 Likes