Lab 2.8: Iterating results (it)

You specified how to iterate to the next batch of 20 results but what about
How to go back to previous iteration?
How to skip to the nth iteration?
How to see how many iterations are available?

Cursors are forward only.

A combination of skip() + 20.

The ceiling of itcount() / 20, however, itcount will exhaust the cursor. When you call itcount(), hasNext() will return false.

See the documentation for reference.

1 Like

Hi @Elijah_04078,

[Edited - 22nd Jan, 2020]

Great question.

Couple of things I would like to add here :

Be default the batch size is 20. You can totally change it to any other value using the DBQuery.shellBatchSize attribute.

You can load the cursor result in the RAM in the form of an array of documents which were present in the cursor using the toArray() method. This will allow you to perform the desired operation.

Well, let’s say you wan to skip to the 100th iteration and your batch size is 20 then you can do something like this :

db.collection_name.find({}).skip(20*99)

Hope it helps!

Please feel free to get back to us if you have any other query.

Thanks,
Shubham Ranjan
Curriculum Services Engineer

1 Like

Should point out that the shell batch size (from 20) can only be changed using DBQuery.shellBatchSize instead of cursor.batchSize()… they are different. It can be tested using cursor.objsLeftInBatch(). The cursor.batchSize is initially 101 and subsequent calls are dependent on MongoDB’s document limits.

And although toArray() provides a way to further manipulate the documents, it returns an array object, not a cursor. Which means, all documents are pulled across! So in essence, there’s no way in MongoDB shell/driver to go backwards because it’s a forward-only cursor, not a dynamic cursor.

2 Likes

Hi @007_jb,

My bad, thanks for pointing it out :slight_smile: .

Yes, it will be an array of documents that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.

Thanks,
Shubham Ranjan
Curriculum Services Engineer