Search code examples
mongodbmemory-leaksmongodb-querydatabase-cursor

MongoDB : Why should we close the cursor after it is used?


I have seen that people close the cursor after it has been used. I also read in documentation that server closes the cursor after 10 minutes of inactivity.

I searched the net but didn't find proper answer. I am new to both database and MongoDB.

Why is it necessary to close the cursor?


Solution

  • Closing the cursor is only really required when you do not "exhaust" the results. Or in other terms, iterate over all the possible results returned by the cursor.

    Leaving a "cursor" open is like leaving an open connection that never gets re-used. These things are not free. In fact the standard connection cost is 1MB (approx). So if you are leaving a lot of "partially iterated" cursors hanging around there is a general overhead in terms of an active connection and it's memory usage.

    If in fact you actually always iterate "all" of the results (and that includes a "limit" which is a "cursor modifier") then the cursor will close and all is okay.

    General usage will be that you actually exhaust/deplete the cursor by going through all of the results. Therefore there is no explicit need to destroy.