In this short article, I would like to tell some basics about the working mechanism of the MongoDB cursor. There’re a lot of cases when service is connected to the database but when requesting data from server it hangs and doesn’t get any response or even error exceptions.
Cursor is a prepared set of documents that contains documents matching current query criteria. In other words when we call .find() method in the server is creating that kind of virtual collection and cursor is pointing to start element of that collection.
With the .find() query there is a possibility to send an option that will tell the server how many documents should be sent back to the client on each batch. That option is called batchSize. So after the first .next() method call, server returns to the client set of documents. Returned documents quantity is equal to batchSize which was set on querying documents or its default value. After that when all cached documents were taken by the client it is asking the server for the next batch. And this process continues until all the batches were taken by the client.
One of the cause of a problem could be calling .find() with sort command. Actually it is not a problem if the field or the fields by which server should sort documents were indexed.