cursor.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. # Copyright 2009-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Cursor class to iterate over Mongo query results."""
  15. import copy
  16. import threading
  17. import warnings
  18. from collections import deque
  19. from bson import RE_TYPE, _convert_raw_document_lists_to_streams
  20. from bson.code import Code
  21. from bson.py3compat import (iteritems,
  22. integer_types,
  23. string_type)
  24. from bson.son import SON
  25. from pymongo import helpers
  26. from pymongo.common import validate_boolean, validate_is_mapping
  27. from pymongo.collation import validate_collation_or_none
  28. from pymongo.errors import (ConnectionFailure,
  29. InvalidOperation,
  30. OperationFailure)
  31. from pymongo.message import (_CursorAddress,
  32. _GetMore,
  33. _RawBatchGetMore,
  34. _Query,
  35. _RawBatchQuery)
  36. from pymongo.response import PinnedResponse
  37. # These errors mean that the server has already killed the cursor so there is
  38. # no need to send killCursors.
  39. _CURSOR_CLOSED_ERRORS = frozenset([
  40. 43, # CursorNotFound
  41. 50, # MaxTimeMSExpired
  42. 175, # QueryPlanKilled
  43. 237, # CursorKilled
  44. # On a tailable cursor, the following errors mean the capped collection
  45. # rolled over.
  46. # MongoDB 2.6:
  47. # {'$err': 'Runner killed during getMore', 'code': 28617, 'ok': 0}
  48. 28617,
  49. # MongoDB 3.0:
  50. # {'$err': 'getMore executor error: UnknownError no details available',
  51. # 'code': 17406, 'ok': 0}
  52. 17406,
  53. # MongoDB 3.2 + 3.4:
  54. # {'ok': 0.0, 'errmsg': 'GetMore command executor error:
  55. # CappedPositionLost: CollectionScan died due to failure to restore
  56. # tailable cursor position. Last seen record id: RecordId(3)',
  57. # 'code': 96}
  58. 96,
  59. # MongoDB 3.6+:
  60. # {'ok': 0.0, 'errmsg': 'errmsg: "CollectionScan died due to failure to
  61. # restore tailable cursor position. Last seen record id: RecordId(3)"',
  62. # 'code': 136, 'codeName': 'CappedPositionLost'}
  63. 136,
  64. ])
  65. _QUERY_OPTIONS = {
  66. "tailable_cursor": 2,
  67. "secondary_okay": 4,
  68. "oplog_replay": 8,
  69. "no_timeout": 16,
  70. "await_data": 32,
  71. "exhaust": 64,
  72. "partial": 128}
  73. class CursorType(object):
  74. NON_TAILABLE = 0
  75. """The standard cursor type."""
  76. TAILABLE = _QUERY_OPTIONS["tailable_cursor"]
  77. """The tailable cursor type.
  78. Tailable cursors are only for use with capped collections. They are not
  79. closed when the last data is retrieved but are kept open and the cursor
  80. location marks the final document position. If more data is received
  81. iteration of the cursor will continue from the last document received.
  82. """
  83. TAILABLE_AWAIT = TAILABLE | _QUERY_OPTIONS["await_data"]
  84. """A tailable cursor with the await option set.
  85. Creates a tailable cursor that will wait for a few seconds after returning
  86. the full result set so that it can capture and return additional data added
  87. during the query.
  88. """
  89. EXHAUST = _QUERY_OPTIONS["exhaust"]
  90. """An exhaust cursor.
  91. MongoDB will stream batched results to the client without waiting for the
  92. client to request each batch, reducing latency.
  93. """
  94. class _SocketManager(object):
  95. """Used with exhaust cursors to ensure the socket is returned.
  96. """
  97. def __init__(self, sock, more_to_come):
  98. self.sock = sock
  99. self.more_to_come = more_to_come
  100. self.closed = False
  101. self.lock = threading.Lock()
  102. def update_exhaust(self, more_to_come):
  103. self.more_to_come = more_to_come
  104. def close(self):
  105. """Return this instance's socket to the connection pool.
  106. """
  107. if not self.closed:
  108. self.closed = True
  109. self.sock.unpin()
  110. self.sock = None
  111. class Cursor(object):
  112. """A cursor / iterator over Mongo query results.
  113. """
  114. _query_class = _Query
  115. _getmore_class = _GetMore
  116. def __init__(self, collection, filter=None, projection=None, skip=0,
  117. limit=0, no_cursor_timeout=False,
  118. cursor_type=CursorType.NON_TAILABLE,
  119. sort=None, allow_partial_results=False, oplog_replay=False,
  120. modifiers=None, batch_size=0, manipulate=True,
  121. collation=None, hint=None, max_scan=None, max_time_ms=None,
  122. max=None, min=None, return_key=False, show_record_id=False,
  123. snapshot=False, comment=None, session=None,
  124. allow_disk_use=None):
  125. """Create a new cursor.
  126. Should not be called directly by application developers - see
  127. :meth:`~pymongo.collection.Collection.find` instead.
  128. .. mongodoc:: cursors
  129. """
  130. # Initialize all attributes used in __del__ before possibly raising
  131. # an error to avoid attribute errors during garbage collection.
  132. self.__collection = collection
  133. self.__id = None
  134. self.__exhaust = False
  135. self.__sock_mgr = None
  136. self.__killed = False
  137. if session:
  138. self.__session = session
  139. self.__explicit_session = True
  140. else:
  141. self.__session = None
  142. self.__explicit_session = False
  143. spec = filter
  144. if spec is None:
  145. spec = {}
  146. validate_is_mapping("filter", spec)
  147. if not isinstance(skip, int):
  148. raise TypeError("skip must be an instance of int")
  149. if not isinstance(limit, int):
  150. raise TypeError("limit must be an instance of int")
  151. validate_boolean("no_cursor_timeout", no_cursor_timeout)
  152. if no_cursor_timeout and not self.__explicit_session:
  153. warnings.warn("use an explicit session with no_cursor_timeout=True "
  154. "otherwise the cursor may still timeout after "
  155. "30 minutes, for more info see "
  156. "https://docs.mongodb.com/v4.4/reference/method/"
  157. "cursor.noCursorTimeout/"
  158. "#session-idle-timeout-overrides-nocursortimeout",
  159. UserWarning, stacklevel=2)
  160. if cursor_type not in (CursorType.NON_TAILABLE, CursorType.TAILABLE,
  161. CursorType.TAILABLE_AWAIT, CursorType.EXHAUST):
  162. raise ValueError("not a valid value for cursor_type")
  163. validate_boolean("allow_partial_results", allow_partial_results)
  164. validate_boolean("oplog_replay", oplog_replay)
  165. if modifiers is not None:
  166. warnings.warn("the 'modifiers' parameter is deprecated",
  167. DeprecationWarning, stacklevel=2)
  168. validate_is_mapping("modifiers", modifiers)
  169. if not isinstance(batch_size, integer_types):
  170. raise TypeError("batch_size must be an integer")
  171. if batch_size < 0:
  172. raise ValueError("batch_size must be >= 0")
  173. # Only set if allow_disk_use is provided by the user, else None.
  174. if allow_disk_use is not None:
  175. allow_disk_use = validate_boolean("allow_disk_use", allow_disk_use)
  176. if projection is not None:
  177. if not projection:
  178. projection = {"_id": 1}
  179. projection = helpers._fields_list_to_dict(projection, "projection")
  180. self.__spec = spec
  181. self.__projection = projection
  182. self.__skip = skip
  183. self.__limit = limit
  184. self.__batch_size = batch_size
  185. self.__modifiers = modifiers and modifiers.copy() or {}
  186. self.__ordering = sort and helpers._index_document(sort) or None
  187. self.__max_scan = max_scan
  188. self.__explain = False
  189. self.__comment = comment
  190. self.__max_time_ms = max_time_ms
  191. self.__max_await_time_ms = None
  192. self.__max = max
  193. self.__min = min
  194. self.__manipulate = manipulate
  195. self.__collation = validate_collation_or_none(collation)
  196. self.__return_key = return_key
  197. self.__show_record_id = show_record_id
  198. self.__allow_disk_use = allow_disk_use
  199. self.__snapshot = snapshot
  200. self.__set_hint(hint)
  201. # Exhaust cursor support
  202. if cursor_type == CursorType.EXHAUST:
  203. if self.__collection.database.client.is_mongos:
  204. raise InvalidOperation('Exhaust cursors are '
  205. 'not supported by mongos')
  206. if limit:
  207. raise InvalidOperation("Can't use limit and exhaust together.")
  208. self.__exhaust = True
  209. # This is ugly. People want to be able to do cursor[5:5] and
  210. # get an empty result set (old behavior was an
  211. # exception). It's hard to do that right, though, because the
  212. # server uses limit(0) to mean 'no limit'. So we set __empty
  213. # in that case and check for it when iterating. We also unset
  214. # it anytime we change __limit.
  215. self.__empty = False
  216. self.__data = deque()
  217. self.__address = None
  218. self.__retrieved = 0
  219. self.__codec_options = collection.codec_options
  220. # Read preference is set when the initial find is sent.
  221. self.__read_preference = None
  222. self.__read_concern = collection.read_concern
  223. self.__query_flags = cursor_type
  224. if no_cursor_timeout:
  225. self.__query_flags |= _QUERY_OPTIONS["no_timeout"]
  226. if allow_partial_results:
  227. self.__query_flags |= _QUERY_OPTIONS["partial"]
  228. if oplog_replay:
  229. self.__query_flags |= _QUERY_OPTIONS["oplog_replay"]
  230. # The namespace to use for find/getMore commands.
  231. self.__dbname = collection.database.name
  232. self.__collname = collection.name
  233. @property
  234. def collection(self):
  235. """The :class:`~pymongo.collection.Collection` that this
  236. :class:`Cursor` is iterating.
  237. """
  238. return self.__collection
  239. @property
  240. def retrieved(self):
  241. """The number of documents retrieved so far.
  242. """
  243. return self.__retrieved
  244. def __del__(self):
  245. self.__die()
  246. def rewind(self):
  247. """Rewind this cursor to its unevaluated state.
  248. Reset this cursor if it has been partially or completely evaluated.
  249. Any options that are present on the cursor will remain in effect.
  250. Future iterating performed on this cursor will cause new queries to
  251. be sent to the server, even if the resultant data has already been
  252. retrieved by this cursor.
  253. """
  254. self.close()
  255. self.__data = deque()
  256. self.__id = None
  257. self.__address = None
  258. self.__retrieved = 0
  259. self.__killed = False
  260. return self
  261. def clone(self):
  262. """Get a clone of this cursor.
  263. Returns a new Cursor instance with options matching those that have
  264. been set on the current instance. The clone will be completely
  265. unevaluated, even if the current instance has been partially or
  266. completely evaluated.
  267. """
  268. return self._clone(True)
  269. def _clone(self, deepcopy=True, base=None):
  270. """Internal clone helper."""
  271. if not base:
  272. if self.__explicit_session:
  273. base = self._clone_base(self.__session)
  274. else:
  275. base = self._clone_base(None)
  276. values_to_clone = ("spec", "projection", "skip", "limit",
  277. "max_time_ms", "max_await_time_ms", "comment",
  278. "max", "min", "ordering", "explain", "hint",
  279. "batch_size", "max_scan", "manipulate",
  280. "query_flags", "modifiers", "collation", "empty",
  281. "show_record_id", "return_key", "allow_disk_use",
  282. "snapshot", "exhaust")
  283. data = dict((k, v) for k, v in iteritems(self.__dict__)
  284. if k.startswith('_Cursor__') and k[9:] in values_to_clone)
  285. if deepcopy:
  286. data = self._deepcopy(data)
  287. base.__dict__.update(data)
  288. return base
  289. def _clone_base(self, session):
  290. """Creates an empty Cursor object for information to be copied into.
  291. """
  292. return self.__class__(self.__collection, session=session)
  293. def __die(self, synchronous=False):
  294. """Closes this cursor.
  295. """
  296. try:
  297. already_killed = self.__killed
  298. except AttributeError:
  299. # __init__ did not run to completion (or at all).
  300. return
  301. self.__killed = True
  302. if self.__id and not already_killed:
  303. cursor_id = self.__id
  304. address = _CursorAddress(
  305. self.__address, "%s.%s" % (self.__dbname, self.__collname))
  306. else:
  307. # Skip killCursors.
  308. cursor_id = 0
  309. address = None
  310. self.__collection.database.client._cleanup_cursor(
  311. synchronous,
  312. cursor_id,
  313. address,
  314. self.__sock_mgr,
  315. self.__session,
  316. self.__explicit_session)
  317. if not self.__explicit_session:
  318. self.__session = None
  319. self.__sock_mgr = None
  320. def close(self):
  321. """Explicitly close / kill this cursor.
  322. """
  323. self.__die(True)
  324. def __query_spec(self):
  325. """Get the spec to use for a query.
  326. """
  327. operators = self.__modifiers.copy()
  328. if self.__ordering:
  329. operators["$orderby"] = self.__ordering
  330. if self.__explain:
  331. operators["$explain"] = True
  332. if self.__hint:
  333. operators["$hint"] = self.__hint
  334. if self.__comment:
  335. operators["$comment"] = self.__comment
  336. if self.__max_scan:
  337. operators["$maxScan"] = self.__max_scan
  338. if self.__max_time_ms is not None:
  339. operators["$maxTimeMS"] = self.__max_time_ms
  340. if self.__max:
  341. operators["$max"] = self.__max
  342. if self.__min:
  343. operators["$min"] = self.__min
  344. if self.__return_key:
  345. operators["$returnKey"] = self.__return_key
  346. if self.__show_record_id:
  347. # This is upgraded to showRecordId for MongoDB 3.2+ "find" command.
  348. operators["$showDiskLoc"] = self.__show_record_id
  349. if self.__snapshot:
  350. operators["$snapshot"] = self.__snapshot
  351. if operators:
  352. # Make a shallow copy so we can cleanly rewind or clone.
  353. spec = self.__spec.copy()
  354. # White-listed commands must be wrapped in $query.
  355. if "$query" not in spec:
  356. # $query has to come first
  357. spec = SON([("$query", spec)])
  358. if not isinstance(spec, SON):
  359. # Ensure the spec is SON. As order is important this will
  360. # ensure its set before merging in any extra operators.
  361. spec = SON(spec)
  362. spec.update(operators)
  363. return spec
  364. # Have to wrap with $query if "query" is the first key.
  365. # We can't just use $query anytime "query" is a key as
  366. # that breaks commands like count and find_and_modify.
  367. # Checking spec.keys()[0] covers the case that the spec
  368. # was passed as an instance of SON or OrderedDict.
  369. elif ("query" in self.__spec and
  370. (len(self.__spec) == 1 or
  371. next(iter(self.__spec)) == "query")):
  372. return SON({"$query": self.__spec})
  373. return self.__spec
  374. def __check_okay_to_chain(self):
  375. """Check if it is okay to chain more options onto this cursor.
  376. """
  377. if self.__retrieved or self.__id is not None:
  378. raise InvalidOperation("cannot set options after executing query")
  379. def add_option(self, mask):
  380. """Set arbitrary query flags using a bitmask.
  381. To set the tailable flag:
  382. cursor.add_option(2)
  383. """
  384. if not isinstance(mask, int):
  385. raise TypeError("mask must be an int")
  386. self.__check_okay_to_chain()
  387. if mask & _QUERY_OPTIONS["exhaust"]:
  388. if self.__limit:
  389. raise InvalidOperation("Can't use limit and exhaust together.")
  390. if self.__collection.database.client.is_mongos:
  391. raise InvalidOperation('Exhaust cursors are '
  392. 'not supported by mongos')
  393. self.__exhaust = True
  394. self.__query_flags |= mask
  395. return self
  396. def remove_option(self, mask):
  397. """Unset arbitrary query flags using a bitmask.
  398. To unset the tailable flag:
  399. cursor.remove_option(2)
  400. """
  401. if not isinstance(mask, int):
  402. raise TypeError("mask must be an int")
  403. self.__check_okay_to_chain()
  404. if mask & _QUERY_OPTIONS["exhaust"]:
  405. self.__exhaust = False
  406. self.__query_flags &= ~mask
  407. return self
  408. def allow_disk_use(self, allow_disk_use):
  409. """Specifies whether MongoDB can use temporary disk files while
  410. processing a blocking sort operation.
  411. Raises :exc:`TypeError` if `allow_disk_use` is not a boolean.
  412. .. note:: `allow_disk_use` requires server version **>= 4.4**
  413. :Parameters:
  414. - `allow_disk_use`: if True, MongoDB may use temporary
  415. disk files to store data exceeding the system memory limit while
  416. processing a blocking sort operation.
  417. .. versionadded:: 3.11
  418. """
  419. if not isinstance(allow_disk_use, bool):
  420. raise TypeError('allow_disk_use must be a bool')
  421. self.__check_okay_to_chain()
  422. self.__allow_disk_use = allow_disk_use
  423. return self
  424. def limit(self, limit):
  425. """Limits the number of results to be returned by this cursor.
  426. Raises :exc:`TypeError` if `limit` is not an integer. Raises
  427. :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
  428. has already been used. The last `limit` applied to this cursor
  429. takes precedence. A limit of ``0`` is equivalent to no limit.
  430. :Parameters:
  431. - `limit`: the number of results to return
  432. .. mongodoc:: limit
  433. """
  434. if not isinstance(limit, integer_types):
  435. raise TypeError("limit must be an integer")
  436. if self.__exhaust:
  437. raise InvalidOperation("Can't use limit and exhaust together.")
  438. self.__check_okay_to_chain()
  439. self.__empty = False
  440. self.__limit = limit
  441. return self
  442. def batch_size(self, batch_size):
  443. """Limits the number of documents returned in one batch. Each batch
  444. requires a round trip to the server. It can be adjusted to optimize
  445. performance and limit data transfer.
  446. .. note:: batch_size can not override MongoDB's internal limits on the
  447. amount of data it will return to the client in a single batch (i.e
  448. if you set batch size to 1,000,000,000, MongoDB will currently only
  449. return 4-16MB of results per batch).
  450. Raises :exc:`TypeError` if `batch_size` is not an integer.
  451. Raises :exc:`ValueError` if `batch_size` is less than ``0``.
  452. Raises :exc:`~pymongo.errors.InvalidOperation` if this
  453. :class:`Cursor` has already been used. The last `batch_size`
  454. applied to this cursor takes precedence.
  455. :Parameters:
  456. - `batch_size`: The size of each batch of results requested.
  457. """
  458. if not isinstance(batch_size, integer_types):
  459. raise TypeError("batch_size must be an integer")
  460. if batch_size < 0:
  461. raise ValueError("batch_size must be >= 0")
  462. self.__check_okay_to_chain()
  463. self.__batch_size = batch_size
  464. return self
  465. def skip(self, skip):
  466. """Skips the first `skip` results of this cursor.
  467. Raises :exc:`TypeError` if `skip` is not an integer. Raises
  468. :exc:`ValueError` if `skip` is less than ``0``. Raises
  469. :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
  470. already been used. The last `skip` applied to this cursor takes
  471. precedence.
  472. :Parameters:
  473. - `skip`: the number of results to skip
  474. """
  475. if not isinstance(skip, integer_types):
  476. raise TypeError("skip must be an integer")
  477. if skip < 0:
  478. raise ValueError("skip must be >= 0")
  479. self.__check_okay_to_chain()
  480. self.__skip = skip
  481. return self
  482. def max_time_ms(self, max_time_ms):
  483. """Specifies a time limit for a query operation. If the specified
  484. time is exceeded, the operation will be aborted and
  485. :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
  486. is ``None`` no limit is applied.
  487. Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``.
  488. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
  489. has already been used.
  490. :Parameters:
  491. - `max_time_ms`: the time limit after which the operation is aborted
  492. """
  493. if (not isinstance(max_time_ms, integer_types)
  494. and max_time_ms is not None):
  495. raise TypeError("max_time_ms must be an integer or None")
  496. self.__check_okay_to_chain()
  497. self.__max_time_ms = max_time_ms
  498. return self
  499. def max_await_time_ms(self, max_await_time_ms):
  500. """Specifies a time limit for a getMore operation on a
  501. :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
  502. types of cursor max_await_time_ms is ignored.
  503. Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or
  504. ``None``. Raises :exc:`~pymongo.errors.InvalidOperation` if this
  505. :class:`Cursor` has already been used.
  506. .. note:: `max_await_time_ms` requires server version **>= 3.2**
  507. :Parameters:
  508. - `max_await_time_ms`: the time limit after which the operation is
  509. aborted
  510. .. versionadded:: 3.2
  511. """
  512. if (not isinstance(max_await_time_ms, integer_types)
  513. and max_await_time_ms is not None):
  514. raise TypeError("max_await_time_ms must be an integer or None")
  515. self.__check_okay_to_chain()
  516. # Ignore max_await_time_ms if not tailable or await_data is False.
  517. if self.__query_flags & CursorType.TAILABLE_AWAIT:
  518. self.__max_await_time_ms = max_await_time_ms
  519. return self
  520. def __getitem__(self, index):
  521. """Get a single document or a slice of documents from this cursor.
  522. .. warning:: A :class:`~Cursor` is not a Python :class:`list`. Each
  523. index access or slice requires that a new query be run using skip
  524. and limit. Do not iterate the cursor using index accesses.
  525. The following example is **extremely inefficient** and may return
  526. surprising results::
  527. cursor = db.collection.find()
  528. # Warning: This runs a new query for each document.
  529. # Don't do this!
  530. for idx in range(10):
  531. print(cursor[idx])
  532. Raises :class:`~pymongo.errors.InvalidOperation` if this
  533. cursor has already been used.
  534. To get a single document use an integral index, e.g.::
  535. >>> db.test.find()[50]
  536. An :class:`IndexError` will be raised if the index is negative
  537. or greater than the amount of documents in this cursor. Any
  538. limit previously applied to this cursor will be ignored.
  539. To get a slice of documents use a slice index, e.g.::
  540. >>> db.test.find()[20:25]
  541. This will return this cursor with a limit of ``5`` and skip of
  542. ``20`` applied. Using a slice index will override any prior
  543. limits or skips applied to this cursor (including those
  544. applied through previous calls to this method). Raises
  545. :class:`IndexError` when the slice has a step, a negative
  546. start value, or a stop value less than or equal to the start
  547. value.
  548. :Parameters:
  549. - `index`: An integer or slice index to be applied to this cursor
  550. """
  551. self.__check_okay_to_chain()
  552. self.__empty = False
  553. if isinstance(index, slice):
  554. if index.step is not None:
  555. raise IndexError("Cursor instances do not support slice steps")
  556. skip = 0
  557. if index.start is not None:
  558. if index.start < 0:
  559. raise IndexError("Cursor instances do not support "
  560. "negative indices")
  561. skip = index.start
  562. if index.stop is not None:
  563. limit = index.stop - skip
  564. if limit < 0:
  565. raise IndexError("stop index must be greater than start "
  566. "index for slice %r" % index)
  567. if limit == 0:
  568. self.__empty = True
  569. else:
  570. limit = 0
  571. self.__skip = skip
  572. self.__limit = limit
  573. return self
  574. if isinstance(index, integer_types):
  575. if index < 0:
  576. raise IndexError("Cursor instances do not support negative "
  577. "indices")
  578. clone = self.clone()
  579. clone.skip(index + self.__skip)
  580. clone.limit(-1) # use a hard limit
  581. clone.__query_flags &= ~CursorType.TAILABLE_AWAIT # PYTHON-1371
  582. for doc in clone:
  583. return doc
  584. raise IndexError("no such item for Cursor instance")
  585. raise TypeError("index %r cannot be applied to Cursor "
  586. "instances" % index)
  587. def max_scan(self, max_scan):
  588. """**DEPRECATED** - Limit the number of documents to scan when
  589. performing the query.
  590. Raises :class:`~pymongo.errors.InvalidOperation` if this
  591. cursor has already been used. Only the last :meth:`max_scan`
  592. applied to this cursor has any effect.
  593. :Parameters:
  594. - `max_scan`: the maximum number of documents to scan
  595. .. versionchanged:: 3.7
  596. Deprecated :meth:`max_scan`. Support for this option is deprecated in
  597. MongoDB 4.0. Use :meth:`max_time_ms` instead to limit server side
  598. execution time.
  599. """
  600. self.__check_okay_to_chain()
  601. self.__max_scan = max_scan
  602. return self
  603. def max(self, spec):
  604. """Adds ``max`` operator that specifies upper bound for specific index.
  605. When using ``max``, :meth:`~hint` should also be configured to ensure
  606. the query uses the expected index and starting in MongoDB 4.2
  607. :meth:`~hint` will be required.
  608. :Parameters:
  609. - `spec`: a list of field, limit pairs specifying the exclusive
  610. upper bound for all keys of a specific index in order.
  611. .. versionchanged:: 3.8
  612. Deprecated cursors that use ``max`` without a :meth:`~hint`.
  613. .. versionadded:: 2.7
  614. """
  615. if not isinstance(spec, (list, tuple)):
  616. raise TypeError("spec must be an instance of list or tuple")
  617. self.__check_okay_to_chain()
  618. self.__max = SON(spec)
  619. return self
  620. def min(self, spec):
  621. """Adds ``min`` operator that specifies lower bound for specific index.
  622. When using ``min``, :meth:`~hint` should also be configured to ensure
  623. the query uses the expected index and starting in MongoDB 4.2
  624. :meth:`~hint` will be required.
  625. :Parameters:
  626. - `spec`: a list of field, limit pairs specifying the inclusive
  627. lower bound for all keys of a specific index in order.
  628. .. versionchanged:: 3.8
  629. Deprecated cursors that use ``min`` without a :meth:`~hint`.
  630. .. versionadded:: 2.7
  631. """
  632. if not isinstance(spec, (list, tuple)):
  633. raise TypeError("spec must be an instance of list or tuple")
  634. self.__check_okay_to_chain()
  635. self.__min = SON(spec)
  636. return self
  637. def sort(self, key_or_list, direction=None):
  638. """Sorts this cursor's results.
  639. Pass a field name and a direction, either
  640. :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
  641. for doc in collection.find().sort('field', pymongo.ASCENDING):
  642. print(doc)
  643. To sort by multiple fields, pass a list of (key, direction) pairs::
  644. for doc in collection.find().sort([
  645. ('field1', pymongo.ASCENDING),
  646. ('field2', pymongo.DESCENDING)]):
  647. print(doc)
  648. Beginning with MongoDB version 2.6, text search results can be
  649. sorted by relevance::
  650. cursor = db.test.find(
  651. {'$text': {'$search': 'some words'}},
  652. {'score': {'$meta': 'textScore'}})
  653. # Sort by 'score' field.
  654. cursor.sort([('score', {'$meta': 'textScore'})])
  655. for doc in cursor:
  656. print(doc)
  657. For more advanced text search functionality, see MongoDB's
  658. `Atlas Search <https://docs.atlas.mongodb.com/atlas-search/>`_.
  659. Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
  660. already been used. Only the last :meth:`sort` applied to this
  661. cursor has any effect.
  662. :Parameters:
  663. - `key_or_list`: a single key or a list of (key, direction)
  664. pairs specifying the keys to sort on
  665. - `direction` (optional): only used if `key_or_list` is a single
  666. key, if not given :data:`~pymongo.ASCENDING` is assumed
  667. """
  668. self.__check_okay_to_chain()
  669. keys = helpers._index_list(key_or_list, direction)
  670. self.__ordering = helpers._index_document(keys)
  671. return self
  672. def count(self, with_limit_and_skip=False):
  673. """**DEPRECATED** - Get the size of the results set for this query.
  674. The :meth:`count` method is deprecated and **not** supported in a
  675. transaction. Please use
  676. :meth:`~pymongo.collection.Collection.count_documents` instead.
  677. Returns the number of documents in the results set for this query. Does
  678. not take :meth:`limit` and :meth:`skip` into account by default - set
  679. `with_limit_and_skip` to ``True`` if that is the desired behavior.
  680. Raises :class:`~pymongo.errors.OperationFailure` on a database error.
  681. When used with MongoDB >= 2.6, :meth:`~count` uses any :meth:`~hint`
  682. applied to the query. In the following example the hint is passed to
  683. the count command:
  684. collection.find({'field': 'value'}).hint('field_1').count()
  685. The :meth:`count` method obeys the
  686. :attr:`~pymongo.collection.Collection.read_preference` of the
  687. :class:`~pymongo.collection.Collection` instance on which
  688. :meth:`~pymongo.collection.Collection.find` was called.
  689. :Parameters:
  690. - `with_limit_and_skip` (optional): take any :meth:`limit` or
  691. :meth:`skip` that has been applied to this cursor into account when
  692. getting the count
  693. .. note:: The `with_limit_and_skip` parameter requires server
  694. version **>= 1.1.4-**
  695. .. versionchanged:: 3.7
  696. Deprecated.
  697. .. versionchanged:: 2.8
  698. The :meth:`~count` method now supports :meth:`~hint`.
  699. """
  700. warnings.warn("count is deprecated. Use Collection.count_documents "
  701. "instead.", DeprecationWarning, stacklevel=2)
  702. validate_boolean("with_limit_and_skip", with_limit_and_skip)
  703. cmd = SON([("count", self.__collection.name),
  704. ("query", self.__spec)])
  705. if self.__max_time_ms is not None:
  706. cmd["maxTimeMS"] = self.__max_time_ms
  707. if self.__comment:
  708. cmd["comment"] = self.__comment
  709. if self.__hint is not None:
  710. cmd["hint"] = self.__hint
  711. if with_limit_and_skip:
  712. if self.__limit:
  713. cmd["limit"] = self.__limit
  714. if self.__skip:
  715. cmd["skip"] = self.__skip
  716. return self.__collection._count(
  717. cmd, self.__collation, session=self.__session)
  718. def distinct(self, key):
  719. """Get a list of distinct values for `key` among all documents
  720. in the result set of this query.
  721. Raises :class:`TypeError` if `key` is not an instance of
  722. :class:`basestring` (:class:`str` in python 3).
  723. The :meth:`distinct` method obeys the
  724. :attr:`~pymongo.collection.Collection.read_preference` of the
  725. :class:`~pymongo.collection.Collection` instance on which
  726. :meth:`~pymongo.collection.Collection.find` was called.
  727. :Parameters:
  728. - `key`: name of key for which we want to get the distinct values
  729. .. seealso:: :meth:`pymongo.collection.Collection.distinct`
  730. """
  731. options = {}
  732. if self.__spec:
  733. options["query"] = self.__spec
  734. if self.__max_time_ms is not None:
  735. options['maxTimeMS'] = self.__max_time_ms
  736. if self.__comment:
  737. options['comment'] = self.__comment
  738. if self.__collation is not None:
  739. options['collation'] = self.__collation
  740. return self.__collection.distinct(
  741. key, session=self.__session, **options)
  742. def explain(self):
  743. """Returns an explain plan record for this cursor.
  744. .. note:: Starting with MongoDB 3.2 :meth:`explain` uses
  745. the default verbosity mode of the `explain command
  746. <https://docs.mongodb.com/manual/reference/command/explain/>`_,
  747. ``allPlansExecution``. To use a different verbosity use
  748. :meth:`~pymongo.database.Database.command` to run the explain
  749. command directly.
  750. .. mongodoc:: explain
  751. """
  752. c = self.clone()
  753. c.__explain = True
  754. # always use a hard limit for explains
  755. if c.__limit:
  756. c.__limit = -abs(c.__limit)
  757. return next(c)
  758. def __set_hint(self, index):
  759. if index is None:
  760. self.__hint = None
  761. return
  762. if isinstance(index, string_type):
  763. self.__hint = index
  764. else:
  765. self.__hint = helpers._index_document(index)
  766. def hint(self, index):
  767. """Adds a 'hint', telling Mongo the proper index to use for the query.
  768. Judicious use of hints can greatly improve query
  769. performance. When doing a query on multiple fields (at least
  770. one of which is indexed) pass the indexed field as a hint to
  771. the query. Raises :class:`~pymongo.errors.OperationFailure` if the
  772. provided hint requires an index that does not exist on this collection,
  773. and raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
  774. already been used.
  775. `index` should be an index as passed to
  776. :meth:`~pymongo.collection.Collection.create_index`
  777. (e.g. ``[('field', ASCENDING)]``) or the name of the index.
  778. If `index` is ``None`` any existing hint for this query is
  779. cleared. The last hint applied to this cursor takes precedence
  780. over all others.
  781. :Parameters:
  782. - `index`: index to hint on (as an index specifier)
  783. .. versionchanged:: 2.8
  784. The :meth:`~hint` method accepts the name of the index.
  785. """
  786. self.__check_okay_to_chain()
  787. self.__set_hint(index)
  788. return self
  789. def comment(self, comment):
  790. """Adds a 'comment' to the cursor.
  791. http://docs.mongodb.org/manual/reference/operator/comment/
  792. :Parameters:
  793. - `comment`: A string to attach to the query to help interpret and
  794. trace the operation in the server logs and in profile data.
  795. .. versionadded:: 2.7
  796. """
  797. self.__check_okay_to_chain()
  798. self.__comment = comment
  799. return self
  800. def where(self, code):
  801. """Adds a `$where`_ clause to this query.
  802. The `code` argument must be an instance of :class:`basestring`
  803. (:class:`str` in python 3) or :class:`~bson.code.Code`
  804. containing a JavaScript expression. This expression will be
  805. evaluated for each document scanned. Only those documents
  806. for which the expression evaluates to *true* will be returned
  807. as results. The keyword *this* refers to the object currently
  808. being scanned. For example::
  809. # Find all documents where field "a" is less than "b" plus "c".
  810. for doc in db.test.find().where('this.a < (this.b + this.c)'):
  811. print(doc)
  812. Raises :class:`TypeError` if `code` is not an instance of
  813. :class:`basestring` (:class:`str` in python 3). Raises
  814. :class:`~pymongo.errors.InvalidOperation` if this
  815. :class:`Cursor` has already been used. Only the last call to
  816. :meth:`where` applied to a :class:`Cursor` has any effect.
  817. .. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code`
  818. with scope variables. Consider using `$expr`_ instead.
  819. :Parameters:
  820. - `code`: JavaScript expression to use as a filter
  821. .. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/
  822. .. _$where: https://docs.mongodb.com/manual/reference/operator/query/where/
  823. """
  824. self.__check_okay_to_chain()
  825. if not isinstance(code, Code):
  826. code = Code(code)
  827. self.__spec["$where"] = code
  828. return self
  829. def collation(self, collation):
  830. """Adds a :class:`~pymongo.collation.Collation` to this query.
  831. This option is only supported on MongoDB 3.4 and above.
  832. Raises :exc:`TypeError` if `collation` is not an instance of
  833. :class:`~pymongo.collation.Collation` or a ``dict``. Raises
  834. :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
  835. already been used. Only the last collation applied to this cursor has
  836. any effect.
  837. :Parameters:
  838. - `collation`: An instance of :class:`~pymongo.collation.Collation`.
  839. """
  840. self.__check_okay_to_chain()
  841. self.__collation = validate_collation_or_none(collation)
  842. return self
  843. def __send_message(self, operation):
  844. """Send a query or getmore operation and handles the response.
  845. If operation is ``None`` this is an exhaust cursor, which reads
  846. the next result batch off the exhaust socket instead of
  847. sending getMore messages to the server.
  848. Can raise ConnectionFailure.
  849. """
  850. client = self.__collection.database.client
  851. # OP_MSG is required to support exhaust cursors with encryption.
  852. if client._encrypter and self.__exhaust:
  853. raise InvalidOperation(
  854. "exhaust cursors do not support auto encryption")
  855. try:
  856. response = client._run_operation(
  857. operation, self._unpack_response, address=self.__address)
  858. except OperationFailure as exc:
  859. if exc.code in _CURSOR_CLOSED_ERRORS or self.__exhaust:
  860. # Don't send killCursors because the cursor is already closed.
  861. self.__killed = True
  862. self.close()
  863. # If this is a tailable cursor the error is likely
  864. # due to capped collection roll over. Setting
  865. # self.__killed to True ensures Cursor.alive will be
  866. # False. No need to re-raise.
  867. if (exc.code in _CURSOR_CLOSED_ERRORS and
  868. self.__query_flags & _QUERY_OPTIONS["tailable_cursor"]):
  869. return
  870. raise
  871. except ConnectionFailure:
  872. # Don't send killCursors because the cursor is already closed.
  873. self.__killed = True
  874. self.close()
  875. raise
  876. except Exception:
  877. self.close()
  878. raise
  879. self.__address = response.address
  880. if isinstance(response, PinnedResponse):
  881. if not self.__sock_mgr:
  882. self.__sock_mgr = _SocketManager(response.socket_info,
  883. response.more_to_come)
  884. cmd_name = operation.name
  885. docs = response.docs
  886. if response.from_command:
  887. if cmd_name != "explain":
  888. cursor = docs[0]['cursor']
  889. self.__id = cursor['id']
  890. if cmd_name == 'find':
  891. documents = cursor['firstBatch']
  892. # Update the namespace used for future getMore commands.
  893. ns = cursor.get('ns')
  894. if ns:
  895. self.__dbname, self.__collname = ns.split('.', 1)
  896. else:
  897. documents = cursor['nextBatch']
  898. self.__data = deque(documents)
  899. self.__retrieved += len(documents)
  900. else:
  901. self.__id = 0
  902. self.__data = deque(docs)
  903. self.__retrieved += len(docs)
  904. else:
  905. self.__id = response.data.cursor_id
  906. self.__data = deque(docs)
  907. self.__retrieved += response.data.number_returned
  908. if self.__id == 0:
  909. # Don't wait for garbage collection to call __del__, return the
  910. # socket and the session to the pool now.
  911. self.close()
  912. if self.__limit and self.__id and self.__limit <= self.__retrieved:
  913. self.close()
  914. def _unpack_response(self, response, cursor_id, codec_options,
  915. user_fields=None, legacy_response=False):
  916. return response.unpack_response(cursor_id, codec_options, user_fields,
  917. legacy_response)
  918. def _read_preference(self):
  919. if self.__read_preference is None:
  920. # Save the read preference for getMore commands.
  921. self.__read_preference = self.__collection._read_preference_for(
  922. self.session)
  923. return self.__read_preference
  924. def _refresh(self):
  925. """Refreshes the cursor with more data from Mongo.
  926. Returns the length of self.__data after refresh. Will exit early if
  927. self.__data is already non-empty. Raises OperationFailure when the
  928. cursor cannot be refreshed due to an error on the query.
  929. """
  930. if len(self.__data) or self.__killed:
  931. return len(self.__data)
  932. if not self.__session:
  933. self.__session = self.__collection.database.client._ensure_session()
  934. if self.__id is None: # Query
  935. if (self.__min or self.__max) and not self.__hint:
  936. warnings.warn("using a min/max query operator without "
  937. "specifying a Cursor.hint is deprecated. A "
  938. "hint will be required when using min/max in "
  939. "PyMongo 4.0",
  940. DeprecationWarning, stacklevel=3)
  941. q = self._query_class(self.__query_flags,
  942. self.__collection.database.name,
  943. self.__collection.name,
  944. self.__skip,
  945. self.__query_spec(),
  946. self.__projection,
  947. self.__codec_options,
  948. self._read_preference(),
  949. self.__limit,
  950. self.__batch_size,
  951. self.__read_concern,
  952. self.__collation,
  953. self.__session,
  954. self.__collection.database.client,
  955. self.__allow_disk_use,
  956. self.__exhaust)
  957. self.__send_message(q)
  958. elif self.__id: # Get More
  959. if self.__limit:
  960. limit = self.__limit - self.__retrieved
  961. if self.__batch_size:
  962. limit = min(limit, self.__batch_size)
  963. else:
  964. limit = self.__batch_size
  965. # Exhaust cursors don't send getMore messages.
  966. g = self._getmore_class(self.__dbname,
  967. self.__collname,
  968. limit,
  969. self.__id,
  970. self.__codec_options,
  971. self._read_preference(),
  972. self.__session,
  973. self.__collection.database.client,
  974. self.__max_await_time_ms,
  975. self.__sock_mgr,
  976. self.__exhaust)
  977. self.__send_message(g)
  978. return len(self.__data)
  979. @property
  980. def alive(self):
  981. """Does this cursor have the potential to return more data?
  982. This is mostly useful with `tailable cursors
  983. <http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_
  984. since they will stop iterating even though they *may* return more
  985. results in the future.
  986. With regular cursors, simply use a for loop instead of :attr:`alive`::
  987. for doc in collection.find():
  988. print(doc)
  989. .. note:: Even if :attr:`alive` is True, :meth:`next` can raise
  990. :exc:`StopIteration`. :attr:`alive` can also be True while iterating
  991. a cursor from a failed server. In this case :attr:`alive` will
  992. return False after :meth:`next` fails to retrieve the next batch
  993. of results from the server.
  994. """
  995. return bool(len(self.__data) or (not self.__killed))
  996. @property
  997. def cursor_id(self):
  998. """Returns the id of the cursor
  999. Useful if you need to manage cursor ids and want to handle killing
  1000. cursors manually using
  1001. :meth:`~pymongo.mongo_client.MongoClient.kill_cursors`
  1002. .. versionadded:: 2.2
  1003. """
  1004. return self.__id
  1005. @property
  1006. def address(self):
  1007. """The (host, port) of the server used, or None.
  1008. .. versionchanged:: 3.0
  1009. Renamed from "conn_id".
  1010. """
  1011. return self.__address
  1012. @property
  1013. def session(self):
  1014. """The cursor's :class:`~pymongo.client_session.ClientSession`, or None.
  1015. .. versionadded:: 3.6
  1016. """
  1017. if self.__explicit_session:
  1018. return self.__session
  1019. def __iter__(self):
  1020. return self
  1021. def next(self):
  1022. """Advance the cursor."""
  1023. if self.__empty:
  1024. raise StopIteration
  1025. if len(self.__data) or self._refresh():
  1026. if self.__manipulate:
  1027. _db = self.__collection.database
  1028. return _db._fix_outgoing(self.__data.popleft(),
  1029. self.__collection)
  1030. else:
  1031. return self.__data.popleft()
  1032. else:
  1033. raise StopIteration
  1034. __next__ = next
  1035. def __enter__(self):
  1036. return self
  1037. def __exit__(self, exc_type, exc_val, exc_tb):
  1038. self.close()
  1039. def __copy__(self):
  1040. """Support function for `copy.copy()`.
  1041. .. versionadded:: 2.4
  1042. """
  1043. return self._clone(deepcopy=False)
  1044. def __deepcopy__(self, memo):
  1045. """Support function for `copy.deepcopy()`.
  1046. .. versionadded:: 2.4
  1047. """
  1048. return self._clone(deepcopy=True)
  1049. def _deepcopy(self, x, memo=None):
  1050. """Deepcopy helper for the data dictionary or list.
  1051. Regular expressions cannot be deep copied but as they are immutable we
  1052. don't have to copy them when cloning.
  1053. """
  1054. if not hasattr(x, 'items'):
  1055. y, is_list, iterator = [], True, enumerate(x)
  1056. else:
  1057. y, is_list, iterator = {}, False, iteritems(x)
  1058. if memo is None:
  1059. memo = {}
  1060. val_id = id(x)
  1061. if val_id in memo:
  1062. return memo.get(val_id)
  1063. memo[val_id] = y
  1064. for key, value in iterator:
  1065. if isinstance(value, (dict, list)) and not isinstance(value, SON):
  1066. value = self._deepcopy(value, memo)
  1067. elif not isinstance(value, RE_TYPE):
  1068. value = copy.deepcopy(value, memo)
  1069. if is_list:
  1070. y.append(value)
  1071. else:
  1072. if not isinstance(key, RE_TYPE):
  1073. key = copy.deepcopy(key, memo)
  1074. y[key] = value
  1075. return y
  1076. class RawBatchCursor(Cursor):
  1077. """A cursor / iterator over raw batches of BSON data from a query result."""
  1078. _query_class = _RawBatchQuery
  1079. _getmore_class = _RawBatchGetMore
  1080. def __init__(self, *args, **kwargs):
  1081. """Create a new cursor / iterator over raw batches of BSON data.
  1082. Should not be called directly by application developers -
  1083. see :meth:`~pymongo.collection.Collection.find_raw_batches`
  1084. instead.
  1085. .. mongodoc:: cursors
  1086. """
  1087. manipulate = kwargs.get('manipulate')
  1088. kwargs['manipulate'] = False
  1089. super(RawBatchCursor, self).__init__(*args, **kwargs)
  1090. # Throw only after cursor's initialized, to prevent errors in __del__.
  1091. if manipulate:
  1092. raise InvalidOperation(
  1093. "Cannot use RawBatchCursor with manipulate=True")
  1094. def _unpack_response(self, response, cursor_id, codec_options,
  1095. user_fields=None, legacy_response=False):
  1096. raw_response = response.raw_response(
  1097. cursor_id, user_fields=user_fields)
  1098. if not legacy_response:
  1099. # OP_MSG returns firstBatch/nextBatch documents as a BSON array
  1100. # Re-assemble the array of documents into a document stream
  1101. _convert_raw_document_lists_to_streams(raw_response[0])
  1102. return raw_response
  1103. def explain(self):
  1104. """Returns an explain plan record for this cursor.
  1105. .. mongodoc:: explain
  1106. """
  1107. clone = self._clone(deepcopy=True, base=Cursor(self.collection))
  1108. return clone.explain()
  1109. def __getitem__(self, index):
  1110. raise InvalidOperation("Cannot call __getitem__ on RawBatchCursor")