title: MongoDb Java Driver: Fetching records using a Cursor
body: <p>From mongodb java driver documentation available at </p>
  
  <p><a href="https://www.mongodb.com/blog/post/getting-started-with-mongodb-and-java-part-ii" rel="nofollow noreferrer">https://www.mongodb.com/blog/post/getting-started-with-mongodb-and-java-part-ii</a></p>
  
  <p>It says the following about the cursor available in the java driver.</p>
  
  <p><em>The cursor will fetch results in batches from the database, so if you run a query that matches a lot of documents, you don’t have to worry that every document is loaded into memory immediately. For most queries, the first batch returned will be 101 documents. But as you iterate over the cursor, the driver will automatically fetch further batches from the server. So you don’t have to worry about managing batching in your application. But you do need to be aware that if you iterate over the whole of the cursor (for example to put it into a List), you will end up fetching all the results and putting them in memory.</em></p>
  
  <p>I find it very confusing. First it says, "as you iterate over the cursor, the driver will automatically fetch further batches from the server", which makes sense as you don't want it the blow up your local memory.
  However, it follows with a contradicting statement which basically says if you iterate over the whole of cursor then, the driver would dump all the records from the server in to your local memory in one go.</p>
  
  <p>I am not able to understand how different these two statements are. What is the difference between iterating over a cursor and iterating over the whole of cursor?</p>
  
  <p>I would like to know how exactly cursors work here and what is the most efficient way to iterate over a cursor so that all the records from the server aren't dumped in to the local memory at once causing a memory leak.</p>