Skip to content

PYTHON-3606 - Document best practice for closing MongoClients and cursors #2465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pymongo/asynchronous/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1776,6 +1776,13 @@ def find(self, *args: Any, **kwargs: Any) -> AsyncCursor[_DocumentType]:
improper type. Returns an instance of
:class:`~pymongo.asynchronous.cursor.AsyncCursor` corresponding to this query.

Best practice is to call :meth:`AsyncCursor.close` when the cursor is no longer needed,
or use the cursor in a with statement::

async with collection.find() as cursor:
async for doc in cursor:
print(doc)

The :meth:`find` method obeys the :attr:`read_preference` of
this :class:`AsyncCollection`.

Expand Down
4 changes: 4 additions & 0 deletions pymongo/asynchronous/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1263,10 +1263,14 @@ async def next(self) -> _DocumentType:
self._exhaust_checked = True
await self._supports_exhaust()
if self._empty:
if self._cursor_type == CursorType.NON_TAILABLE:
await self.close()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a bug fix? If so should we create a new bug ticket for it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll open a ticket for this. Empty cursors should always be immediately closed.

raise StopAsyncIteration
if len(self._data) or await self._refresh():
return self._data.popleft()
else:
if self._cursor_type == CursorType.NON_TAILABLE:
await self.close()
Copy link
Member

@ShaneHarvey ShaneHarvey Aug 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this close is redundant since _send_message() already calls close after receiving the final batch. Or is there another case where the cursor would be left open?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the use case when a cursor is not automatically closed (outside of a context manager) is when a user doesn't fully iterate through it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah only an non-exhausted cursor is left open. Even then the cursor is closed at a later point by our GC hooks (via the kill cursor thread) but closing explicitly has stronger guarantees.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case, I think a docstring update alone is sufficient. Explicitly calling out that if you don't fully iterate a cursor, you should close it explicitly feels much more actionable than "always use a context manager".

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docs only SGTM. It could explain the close behavior and then say something like "The best practice to ensure the cursor is always closed promptly is to use a context manager..."

raise StopAsyncIteration

async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg]
Expand Down
6 changes: 6 additions & 0 deletions pymongo/asynchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ def __init__(
exception (recognizing that the operation failed) and then continue to
execute.
Best practice is to call :meth:`AsyncMongoClient.close` when the client is no longer needed,
or use the client in a with statement::
with AsyncMongoClient(url) as client:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be "async with"?

# Use client here.
The `host` parameter can be a full `mongodb URI
<https://dochub.mongodb.org/core/connections>`_, in addition to
a simple hostname. It can also be a list of hostnames but no more
Expand Down
7 changes: 7 additions & 0 deletions pymongo/synchronous/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1775,6 +1775,13 @@ def find(self, *args: Any, **kwargs: Any) -> Cursor[_DocumentType]:
improper type. Returns an instance of
:class:`~pymongo.cursor.Cursor` corresponding to this query.

Best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
or use the cursor in a with statement::

with collection.find() as cursor:
for doc in cursor:
print(doc)

The :meth:`find` method obeys the :attr:`read_preference` of
this :class:`Collection`.

Expand Down
4 changes: 4 additions & 0 deletions pymongo/synchronous/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1261,10 +1261,14 @@ def next(self) -> _DocumentType:
self._exhaust_checked = True
self._supports_exhaust()
if self._empty:
if self._cursor_type == CursorType.NON_TAILABLE:
self.close()
raise StopIteration
if len(self._data) or self._refresh():
return self._data.popleft()
else:
if self._cursor_type == CursorType.NON_TAILABLE:
self.close()
raise StopIteration

def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg]
Expand Down
6 changes: 6 additions & 0 deletions pymongo/synchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ def __init__(
exception (recognizing that the operation failed) and then continue to
execute.

Best practice is to call :meth:`MongoClient.close` when the client is no longer needed,
or use the client in a with statement::

with MongoClient(url) as client:
# Use client here.

The `host` parameter can be a full `mongodb URI
<https://dochub.mongodb.org/core/connections>`_, in addition to
a simple hostname. It can also be a list of hostnames but no more
Expand Down
Loading