Skip to content

Commit 028200b

Browse files
committed
PYTHON-2766 Warn users away from cursor slices
(cherry picked from commit 8848029)
1 parent 9d562f0 commit 028200b

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

doc/api/pymongo/cursor.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
.. describe:: c[index]
2222

23-
See :meth:`__getitem__`.
23+
See :meth:`__getitem__` and read the warning.
2424

2525
.. automethod:: __getitem__
2626

pymongo/cursor.py

+12
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,18 @@ def max_await_time_ms(self, max_await_time_ms):
616616
def __getitem__(self, index):
617617
"""Get a single document or a slice of documents from this cursor.
618618
619+
.. warning:: A :class:`~Cursor` is not a Python :class:`list`. Each
620+
index access or slice requires that a new query be run using skip
621+
and limit. Do not iterate the cursor using index accesses.
622+
The following example is **extremely inefficient** and may return
623+
surprising results::
624+
625+
cursor = db.collection.find()
626+
# Warning: This runs a new query for each document.
627+
# Don't do this!
628+
for idx in range(10):
629+
print(cursor[idx])
630+
619631
Raises :class:`~pymongo.errors.InvalidOperation` if this
620632
cursor has already been used.
621633

0 commit comments

Comments
 (0)