Fetch Records in batches by cursors

I am new to MongoDB. I am currently working with cursors. I need to fetch records from the server side in batches using cursors.
lets say I have 12 records and i want to fetch 5 at a time . The cursor iterator has to go 3 times and fetch 5,5,2 .I wanted to know how i can use while (cursor.hasNext ) loop for this.
Any help is much appreciated.

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: https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-1

2 Likes