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?
Cursors are automatically closed by the mongo server when they're inactive for more than 10 minutes, or if the client has exhausted the cursor. The MongoDB docs recommend either closing cursors, or ensuring they're exhausted by the client.
In MongoDB, when the find() method is used to find the documents present in the given collection, then this method returned a pointer which will points to the documents of the collection, now this pointer is known as cursor.
The Cursor is a MongoDB Collection of the document which is returned upon the find method execution. By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. It is just like a pointer which is pointing upon a specific index value.
Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.
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.
It depends on your usage, but at least in my web application - the client handles the closing. Why? because my web application follows the pattern of short & stateless request handling (you get a request from the browser, build an HTTP response quickly - less than a second - and this response relies on mongo data). So my client only needs the connection for 1 second.
Now, consider what if I have (say) 50 requests per minute... my server handles them comfortably. But it would have crashed if each request were to hold on to resources for 10 minutes... E.g. after 9 minutes I would have 450 unnecessary open resources...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With