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

筅森魡賤 提交于 2019-11-30 07:34:21

问题


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?


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/24260677/mongodb-why-should-we-close-the-cursor-after-it-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!