@@ -1260,16 +1260,20 @@ async def next(self) -> _DocumentType:
12601260 else :
12611261 raise StopAsyncIteration
12621262
1263- async def _next_batch (self , result : list ) -> bool :
1264- """Get all available documents from the cursor."""
1263+ async def _next_batch (self , result : list , total : Optional [ int ] = None ) -> bool :
1264+ """Get all or some documents from the cursor."""
12651265 if not self ._exhaust_checked :
12661266 self ._exhaust_checked = True
12671267 await self ._supports_exhaust ()
12681268 if self ._empty :
12691269 return False
12701270 if len (self ._data ) or await self ._refresh ():
1271- result .extend (self ._data )
1272- self ._data .clear ()
1271+ if total is None :
1272+ result .extend (self ._data )
1273+ self ._data .clear ()
1274+ else :
1275+ for _ in range (min (len (self ._data ), total )):
1276+ result .append (self ._data .popleft ())
12731277 return True
12741278 else :
12751279 return False
@@ -1286,21 +1290,32 @@ async def __aenter__(self) -> AsyncCursor[_DocumentType]:
12861290 async def __aexit__ (self , exc_type : Any , exc_val : Any , exc_tb : Any ) -> None :
12871291 await self .close ()
12881292
1289- async def to_list (self ) -> list [_DocumentType ]:
1293+ async def to_list (self , length : Optional [ int ] = None ) -> list [_DocumentType ]:
12901294 """Converts the contents of this cursor to a list more efficiently than ``[doc async for doc in cursor]``.
12911295
12921296 To use::
12931297
12941298 >>> await cursor.to_list()
12951299
1300+ Or, so read at most n items from the cursor::
1301+
1302+ >>> await cursor.to_list(n)
1303+
12961304 If the cursor is empty or has no more results, an empty list will be returned.
12971305
12981306 .. versionadded:: 4.9
12991307 """
13001308 res : list [_DocumentType ] = []
1309+ remaining = length
1310+ if isinstance (length , int ) and length < 1 :
1311+ raise ValueError ("to_list() length must be greater than 0" )
13011312 while self .alive :
1302- if not await self ._next_batch (res ):
1313+ if not await self ._next_batch (res , remaining ):
13031314 break
1315+ if length is not None :
1316+ remaining = length - len (res )
1317+ if remaining == 0 :
1318+ break
13041319 return res
13051320
13061321
0 commit comments