database.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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. """Database level operations."""
  15. import warnings
  16. from bson.code import Code
  17. from bson.codec_options import DEFAULT_CODEC_OPTIONS
  18. from bson.dbref import DBRef
  19. from bson.py3compat import iteritems, string_type, _unicode
  20. from bson.son import SON
  21. from pymongo import auth, common
  22. from pymongo.aggregation import _DatabaseAggregationCommand
  23. from pymongo.change_stream import DatabaseChangeStream
  24. from pymongo.collection import Collection
  25. from pymongo.command_cursor import CommandCursor
  26. from pymongo.errors import (CollectionInvalid,
  27. ConfigurationError,
  28. InvalidName,
  29. OperationFailure)
  30. from pymongo.hello_compat import HelloCompat
  31. from pymongo.message import _first_batch
  32. from pymongo.read_preferences import ReadPreference
  33. from pymongo.son_manipulator import SONManipulator
  34. from pymongo.write_concern import DEFAULT_WRITE_CONCERN
  35. _INDEX_REGEX = {"name": {"$regex": r"^(?!.*\$)"}}
  36. _SYSTEM_FILTER = {"filter": {"name": {"$regex": r"^(?!system\.)"}}}
  37. def _check_name(name):
  38. """Check if a database name is valid.
  39. """
  40. if not name:
  41. raise InvalidName("database name cannot be the empty string")
  42. for invalid_char in [' ', '.', '$', '/', '\\', '\x00', '"']:
  43. if invalid_char in name:
  44. raise InvalidName("database names cannot contain the "
  45. "character %r" % invalid_char)
  46. class Database(common.BaseObject):
  47. """A Mongo database.
  48. """
  49. def __init__(self, client, name, codec_options=None, read_preference=None,
  50. write_concern=None, read_concern=None):
  51. """Get a database by client and name.
  52. Raises :class:`TypeError` if `name` is not an instance of
  53. :class:`basestring` (:class:`str` in python 3). Raises
  54. :class:`~pymongo.errors.InvalidName` if `name` is not a valid
  55. database name.
  56. :Parameters:
  57. - `client`: A :class:`~pymongo.mongo_client.MongoClient` instance.
  58. - `name`: The database name.
  59. - `codec_options` (optional): An instance of
  60. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  61. default) client.codec_options is used.
  62. - `read_preference` (optional): The read preference to use. If
  63. ``None`` (the default) client.read_preference is used.
  64. - `write_concern` (optional): An instance of
  65. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  66. default) client.write_concern is used.
  67. - `read_concern` (optional): An instance of
  68. :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
  69. default) client.read_concern is used.
  70. .. mongodoc:: databases
  71. .. versionchanged:: 3.2
  72. Added the read_concern option.
  73. .. versionchanged:: 3.0
  74. Added the codec_options, read_preference, and write_concern options.
  75. :class:`~pymongo.database.Database` no longer returns an instance
  76. of :class:`~pymongo.collection.Collection` for attribute names
  77. with leading underscores. You must use dict-style lookups instead::
  78. db['__my_collection__']
  79. Not:
  80. db.__my_collection__
  81. """
  82. super(Database, self).__init__(
  83. codec_options or client.codec_options,
  84. read_preference or client.read_preference,
  85. write_concern or client.write_concern,
  86. read_concern or client.read_concern)
  87. if not isinstance(name, string_type):
  88. raise TypeError("name must be an instance "
  89. "of %s" % (string_type.__name__,))
  90. if name != '$external':
  91. _check_name(name)
  92. self.__name = _unicode(name)
  93. self.__client = client
  94. self.__incoming_manipulators = []
  95. self.__incoming_copying_manipulators = []
  96. self.__outgoing_manipulators = []
  97. self.__outgoing_copying_manipulators = []
  98. def add_son_manipulator(self, manipulator):
  99. """Add a new son manipulator to this database.
  100. **DEPRECATED** - `add_son_manipulator` is deprecated.
  101. .. versionchanged:: 3.0
  102. Deprecated add_son_manipulator.
  103. """
  104. warnings.warn("add_son_manipulator is deprecated",
  105. DeprecationWarning, stacklevel=2)
  106. base = SONManipulator()
  107. def method_overwritten(instance, method):
  108. """Test if this method has been overridden."""
  109. return (getattr(
  110. instance, method).__func__ != getattr(base, method).__func__)
  111. if manipulator.will_copy():
  112. if method_overwritten(manipulator, "transform_incoming"):
  113. self.__incoming_copying_manipulators.insert(0, manipulator)
  114. if method_overwritten(manipulator, "transform_outgoing"):
  115. self.__outgoing_copying_manipulators.insert(0, manipulator)
  116. else:
  117. if method_overwritten(manipulator, "transform_incoming"):
  118. self.__incoming_manipulators.insert(0, manipulator)
  119. if method_overwritten(manipulator, "transform_outgoing"):
  120. self.__outgoing_manipulators.insert(0, manipulator)
  121. @property
  122. def system_js(self):
  123. """**DEPRECATED**: :class:`SystemJS` helper for this :class:`Database`.
  124. See the documentation for :class:`SystemJS` for more details.
  125. """
  126. return SystemJS(self)
  127. @property
  128. def client(self):
  129. """The client instance for this :class:`Database`."""
  130. return self.__client
  131. @property
  132. def name(self):
  133. """The name of this :class:`Database`."""
  134. return self.__name
  135. @property
  136. def incoming_manipulators(self):
  137. """**DEPRECATED**: All incoming SON manipulators.
  138. .. versionchanged:: 3.5
  139. Deprecated.
  140. .. versionadded:: 2.0
  141. """
  142. warnings.warn("Database.incoming_manipulators() is deprecated",
  143. DeprecationWarning, stacklevel=2)
  144. return [manipulator.__class__.__name__
  145. for manipulator in self.__incoming_manipulators]
  146. @property
  147. def incoming_copying_manipulators(self):
  148. """**DEPRECATED**: All incoming SON copying manipulators.
  149. .. versionchanged:: 3.5
  150. Deprecated.
  151. .. versionadded:: 2.0
  152. """
  153. warnings.warn("Database.incoming_copying_manipulators() is deprecated",
  154. DeprecationWarning, stacklevel=2)
  155. return [manipulator.__class__.__name__
  156. for manipulator in self.__incoming_copying_manipulators]
  157. @property
  158. def outgoing_manipulators(self):
  159. """**DEPRECATED**: All outgoing SON manipulators.
  160. .. versionchanged:: 3.5
  161. Deprecated.
  162. .. versionadded:: 2.0
  163. """
  164. warnings.warn("Database.outgoing_manipulators() is deprecated",
  165. DeprecationWarning, stacklevel=2)
  166. return [manipulator.__class__.__name__
  167. for manipulator in self.__outgoing_manipulators]
  168. @property
  169. def outgoing_copying_manipulators(self):
  170. """**DEPRECATED**: All outgoing SON copying manipulators.
  171. .. versionchanged:: 3.5
  172. Deprecated.
  173. .. versionadded:: 2.0
  174. """
  175. warnings.warn("Database.outgoing_copying_manipulators() is deprecated",
  176. DeprecationWarning, stacklevel=2)
  177. return [manipulator.__class__.__name__
  178. for manipulator in self.__outgoing_copying_manipulators]
  179. def with_options(self, codec_options=None, read_preference=None,
  180. write_concern=None, read_concern=None):
  181. """Get a clone of this database changing the specified settings.
  182. >>> db1.read_preference
  183. Primary()
  184. >>> from pymongo import ReadPreference
  185. >>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY)
  186. >>> db1.read_preference
  187. Primary()
  188. >>> db2.read_preference
  189. Secondary(tag_sets=None)
  190. :Parameters:
  191. - `codec_options` (optional): An instance of
  192. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  193. default) the :attr:`codec_options` of this :class:`Collection`
  194. is used.
  195. - `read_preference` (optional): The read preference to use. If
  196. ``None`` (the default) the :attr:`read_preference` of this
  197. :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
  198. for options.
  199. - `write_concern` (optional): An instance of
  200. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  201. default) the :attr:`write_concern` of this :class:`Collection`
  202. is used.
  203. - `read_concern` (optional): An instance of
  204. :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
  205. default) the :attr:`read_concern` of this :class:`Collection`
  206. is used.
  207. .. versionadded:: 3.8
  208. """
  209. return Database(self.client,
  210. self.__name,
  211. codec_options or self.codec_options,
  212. read_preference or self.read_preference,
  213. write_concern or self.write_concern,
  214. read_concern or self.read_concern)
  215. def __eq__(self, other):
  216. if isinstance(other, Database):
  217. return (self.__client == other.client and
  218. self.__name == other.name)
  219. return NotImplemented
  220. def __ne__(self, other):
  221. return not self == other
  222. def __hash__(self):
  223. return hash((self.__client, self.__name))
  224. def __repr__(self):
  225. return "Database(%r, %r)" % (self.__client, self.__name)
  226. def __getattr__(self, name):
  227. """Get a collection of this database by name.
  228. Raises InvalidName if an invalid collection name is used.
  229. :Parameters:
  230. - `name`: the name of the collection to get
  231. """
  232. if name.startswith('_'):
  233. raise AttributeError(
  234. "Database has no attribute %r. To access the %s"
  235. " collection, use database[%r]." % (name, name, name))
  236. return self.__getitem__(name)
  237. def __getitem__(self, name):
  238. """Get a collection of this database by name.
  239. Raises InvalidName if an invalid collection name is used.
  240. :Parameters:
  241. - `name`: the name of the collection to get
  242. """
  243. return Collection(self, name)
  244. def get_collection(self, name, codec_options=None, read_preference=None,
  245. write_concern=None, read_concern=None):
  246. """Get a :class:`~pymongo.collection.Collection` with the given name
  247. and options.
  248. Useful for creating a :class:`~pymongo.collection.Collection` with
  249. different codec options, read preference, and/or write concern from
  250. this :class:`Database`.
  251. >>> db.read_preference
  252. Primary()
  253. >>> coll1 = db.test
  254. >>> coll1.read_preference
  255. Primary()
  256. >>> from pymongo import ReadPreference
  257. >>> coll2 = db.get_collection(
  258. ... 'test', read_preference=ReadPreference.SECONDARY)
  259. >>> coll2.read_preference
  260. Secondary(tag_sets=None)
  261. :Parameters:
  262. - `name`: The name of the collection - a string.
  263. - `codec_options` (optional): An instance of
  264. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  265. default) the :attr:`codec_options` of this :class:`Database` is
  266. used.
  267. - `read_preference` (optional): The read preference to use. If
  268. ``None`` (the default) the :attr:`read_preference` of this
  269. :class:`Database` is used. See :mod:`~pymongo.read_preferences`
  270. for options.
  271. - `write_concern` (optional): An instance of
  272. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  273. default) the :attr:`write_concern` of this :class:`Database` is
  274. used.
  275. - `read_concern` (optional): An instance of
  276. :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
  277. default) the :attr:`read_concern` of this :class:`Database` is
  278. used.
  279. """
  280. return Collection(
  281. self, name, False, codec_options, read_preference,
  282. write_concern, read_concern)
  283. def create_collection(self, name, codec_options=None,
  284. read_preference=None, write_concern=None,
  285. read_concern=None, session=None, **kwargs):
  286. """Create a new :class:`~pymongo.collection.Collection` in this
  287. database.
  288. Normally collection creation is automatic. This method should
  289. only be used to specify options on
  290. creation. :class:`~pymongo.errors.CollectionInvalid` will be
  291. raised if the collection already exists.
  292. Options should be passed as keyword arguments to this method. Supported
  293. options vary with MongoDB release. Some examples include:
  294. - ``size``: desired initial size for the collection (in
  295. bytes). For capped collections this size is the max
  296. size of the collection.
  297. - ``capped``: if True, this is a capped collection
  298. - ``max``: maximum number of objects if capped (optional)
  299. - ``timeseries``: a document specifying configuration options for
  300. timeseries collections
  301. - ``expireAfterSeconds``: the number of seconds after which a
  302. document in a timeseries collection expires
  303. See the MongoDB documentation for a full list of supported options by
  304. server version.
  305. :Parameters:
  306. - `name`: the name of the collection to create
  307. - `codec_options` (optional): An instance of
  308. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  309. default) the :attr:`codec_options` of this :class:`Database` is
  310. used.
  311. - `read_preference` (optional): The read preference to use. If
  312. ``None`` (the default) the :attr:`read_preference` of this
  313. :class:`Database` is used.
  314. - `write_concern` (optional): An instance of
  315. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  316. default) the :attr:`write_concern` of this :class:`Database` is
  317. used.
  318. - `read_concern` (optional): An instance of
  319. :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
  320. default) the :attr:`read_concern` of this :class:`Database` is
  321. used.
  322. - `collation` (optional): An instance of
  323. :class:`~pymongo.collation.Collation`.
  324. - `session` (optional): a
  325. :class:`~pymongo.client_session.ClientSession`.
  326. - `**kwargs` (optional): additional keyword arguments will
  327. be passed as options for the create collection command
  328. .. versionchanged:: 3.11
  329. This method is now supported inside multi-document transactions
  330. with MongoDB 4.4+.
  331. .. versionchanged:: 3.6
  332. Added ``session`` parameter.
  333. .. versionchanged:: 3.4
  334. Added the collation option.
  335. .. versionchanged:: 3.0
  336. Added the codec_options, read_preference, and write_concern options.
  337. .. versionchanged:: 2.2
  338. Removed deprecated argument: options
  339. """
  340. with self.__client._tmp_session(session) as s:
  341. # Skip this check in a transaction where listCollections is not
  342. # supported.
  343. if ((not s or not s.in_transaction) and
  344. name in self.list_collection_names(
  345. filter={"name": name}, session=s)):
  346. raise CollectionInvalid("collection %s already exists" % name)
  347. return Collection(self, name, True, codec_options,
  348. read_preference, write_concern,
  349. read_concern, session=s, **kwargs)
  350. def _apply_incoming_manipulators(self, son, collection):
  351. """Apply incoming manipulators to `son`."""
  352. for manipulator in self.__incoming_manipulators:
  353. son = manipulator.transform_incoming(son, collection)
  354. return son
  355. def _apply_incoming_copying_manipulators(self, son, collection):
  356. """Apply incoming copying manipulators to `son`."""
  357. for manipulator in self.__incoming_copying_manipulators:
  358. son = manipulator.transform_incoming(son, collection)
  359. return son
  360. def _fix_incoming(self, son, collection):
  361. """Apply manipulators to an incoming SON object before it gets stored.
  362. :Parameters:
  363. - `son`: the son object going into the database
  364. - `collection`: the collection the son object is being saved in
  365. """
  366. son = self._apply_incoming_manipulators(son, collection)
  367. son = self._apply_incoming_copying_manipulators(son, collection)
  368. return son
  369. def _fix_outgoing(self, son, collection):
  370. """Apply manipulators to a SON object as it comes out of the database.
  371. :Parameters:
  372. - `son`: the son object coming out of the database
  373. - `collection`: the collection the son object was saved in
  374. """
  375. for manipulator in reversed(self.__outgoing_manipulators):
  376. son = manipulator.transform_outgoing(son, collection)
  377. for manipulator in reversed(self.__outgoing_copying_manipulators):
  378. son = manipulator.transform_outgoing(son, collection)
  379. return son
  380. def aggregate(self, pipeline, session=None, **kwargs):
  381. """Perform a database-level aggregation.
  382. See the `aggregation pipeline`_ documentation for a list of stages
  383. that are supported.
  384. Introduced in MongoDB 3.6.
  385. .. code-block:: python
  386. # Lists all operations currently running on the server.
  387. with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
  388. for operation in cursor:
  389. print(operation)
  390. All optional `aggregate command`_ parameters should be passed as
  391. keyword arguments to this method. Valid options include, but are not
  392. limited to:
  393. - `allowDiskUse` (bool): Enables writing to temporary files. When set
  394. to True, aggregation stages can write data to the _tmp subdirectory
  395. of the --dbpath directory. The default is False.
  396. - `maxTimeMS` (int): The maximum amount of time to allow the operation
  397. to run in milliseconds.
  398. - `batchSize` (int): The maximum number of documents to return per
  399. batch. Ignored if the connected mongod or mongos does not support
  400. returning aggregate results using a cursor.
  401. - `collation` (optional): An instance of
  402. :class:`~pymongo.collation.Collation`.
  403. The :meth:`aggregate` method obeys the :attr:`read_preference` of this
  404. :class:`Database`, except when ``$out`` or ``$merge`` are used, in
  405. which case :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`
  406. is used.
  407. .. note:: This method does not support the 'explain' option. Please
  408. use :meth:`~pymongo.database.Database.command` instead.
  409. .. note:: The :attr:`~pymongo.database.Database.write_concern` of
  410. this collection is automatically applied to this operation.
  411. :Parameters:
  412. - `pipeline`: a list of aggregation pipeline stages
  413. - `session` (optional): a
  414. :class:`~pymongo.client_session.ClientSession`.
  415. - `**kwargs` (optional): See list of options above.
  416. :Returns:
  417. A :class:`~pymongo.command_cursor.CommandCursor` over the result
  418. set.
  419. .. versionadded:: 3.9
  420. .. _aggregation pipeline:
  421. https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline
  422. .. _aggregate command:
  423. https://docs.mongodb.com/manual/reference/command/aggregate
  424. """
  425. with self.client._tmp_session(session, close=False) as s:
  426. cmd = _DatabaseAggregationCommand(
  427. self, CommandCursor, pipeline, kwargs, session is not None,
  428. user_fields={'cursor': {'firstBatch': 1}})
  429. return self.client._retryable_read(
  430. cmd.get_cursor, cmd.get_read_preference(s), s,
  431. retryable=not cmd._performs_write)
  432. def watch(self, pipeline=None, full_document=None, resume_after=None,
  433. max_await_time_ms=None, batch_size=None, collation=None,
  434. start_at_operation_time=None, session=None, start_after=None):
  435. """Watch changes on this database.
  436. Performs an aggregation with an implicit initial ``$changeStream``
  437. stage and returns a
  438. :class:`~pymongo.change_stream.DatabaseChangeStream` cursor which
  439. iterates over changes on all collections in this database.
  440. Introduced in MongoDB 4.0.
  441. .. code-block:: python
  442. with db.watch() as stream:
  443. for change in stream:
  444. print(change)
  445. The :class:`~pymongo.change_stream.DatabaseChangeStream` iterable
  446. blocks until the next change document is returned or an error is
  447. raised. If the
  448. :meth:`~pymongo.change_stream.DatabaseChangeStream.next` method
  449. encounters a network error when retrieving a batch from the server,
  450. it will automatically attempt to recreate the cursor such that no
  451. change events are missed. Any error encountered during the resume
  452. attempt indicates there may be an outage and will be raised.
  453. .. code-block:: python
  454. try:
  455. with db.watch(
  456. [{'$match': {'operationType': 'insert'}}]) as stream:
  457. for insert_change in stream:
  458. print(insert_change)
  459. except pymongo.errors.PyMongoError:
  460. # The ChangeStream encountered an unrecoverable error or the
  461. # resume attempt failed to recreate the cursor.
  462. logging.error('...')
  463. For a precise description of the resume process see the
  464. `change streams specification`_.
  465. :Parameters:
  466. - `pipeline` (optional): A list of aggregation pipeline stages to
  467. append to an initial ``$changeStream`` stage. Not all
  468. pipeline stages are valid after a ``$changeStream`` stage, see the
  469. MongoDB documentation on change streams for the supported stages.
  470. - `full_document` (optional): The fullDocument to pass as an option
  471. to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
  472. When set to 'updateLookup', the change notification for partial
  473. updates will include both a delta describing the changes to the
  474. document, as well as a copy of the entire document that was
  475. changed from some time after the change occurred.
  476. - `resume_after` (optional): A resume token. If provided, the
  477. change stream will start returning changes that occur directly
  478. after the operation specified in the resume token. A resume token
  479. is the _id value of a change document.
  480. - `max_await_time_ms` (optional): The maximum time in milliseconds
  481. for the server to wait for changes before responding to a getMore
  482. operation.
  483. - `batch_size` (optional): The maximum number of documents to return
  484. per batch.
  485. - `collation` (optional): The :class:`~pymongo.collation.Collation`
  486. to use for the aggregation.
  487. - `start_at_operation_time` (optional): If provided, the resulting
  488. change stream will only return changes that occurred at or after
  489. the specified :class:`~bson.timestamp.Timestamp`. Requires
  490. MongoDB >= 4.0.
  491. - `session` (optional): a
  492. :class:`~pymongo.client_session.ClientSession`.
  493. - `start_after` (optional): The same as `resume_after` except that
  494. `start_after` can resume notifications after an invalidate event.
  495. This option and `resume_after` are mutually exclusive.
  496. :Returns:
  497. A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor.
  498. .. versionchanged:: 3.9
  499. Added the ``start_after`` parameter.
  500. .. versionadded:: 3.7
  501. .. mongodoc:: changeStreams
  502. .. _change streams specification:
  503. https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
  504. """
  505. return DatabaseChangeStream(
  506. self, pipeline, full_document, resume_after, max_await_time_ms,
  507. batch_size, collation, start_at_operation_time, session,
  508. start_after)
  509. def _command(self, sock_info, command, secondary_ok=False, value=1,
  510. check=True, allowable_errors=None,
  511. read_preference=ReadPreference.PRIMARY,
  512. codec_options=DEFAULT_CODEC_OPTIONS,
  513. write_concern=None,
  514. parse_write_concern_error=False, session=None, **kwargs):
  515. """Internal command helper."""
  516. if isinstance(command, string_type):
  517. command = SON([(command, value)])
  518. command.update(kwargs)
  519. with self.__client._tmp_session(session) as s:
  520. return sock_info.command(
  521. self.__name,
  522. command,
  523. secondary_ok,
  524. read_preference,
  525. codec_options,
  526. check,
  527. allowable_errors,
  528. write_concern=write_concern,
  529. parse_write_concern_error=parse_write_concern_error,
  530. session=s,
  531. client=self.__client)
  532. def command(self, command, value=1, check=True,
  533. allowable_errors=None, read_preference=None,
  534. codec_options=DEFAULT_CODEC_OPTIONS, session=None, **kwargs):
  535. """Issue a MongoDB command.
  536. Send command `command` to the database and return the
  537. response. If `command` is an instance of :class:`basestring`
  538. (:class:`str` in python 3) then the command {`command`: `value`}
  539. will be sent. Otherwise, `command` must be an instance of
  540. :class:`dict` and will be sent as is.
  541. Any additional keyword arguments will be added to the final
  542. command document before it is sent.
  543. For example, a command like ``{buildinfo: 1}`` can be sent
  544. using:
  545. >>> db.command("buildinfo")
  546. For a command where the value matters, like ``{collstats:
  547. collection_name}`` we can do:
  548. >>> db.command("collstats", collection_name)
  549. For commands that take additional arguments we can use
  550. kwargs. So ``{filemd5: object_id, root: file_root}`` becomes:
  551. >>> db.command("filemd5", object_id, root=file_root)
  552. :Parameters:
  553. - `command`: document representing the command to be issued,
  554. or the name of the command (for simple commands only).
  555. .. note:: the order of keys in the `command` document is
  556. significant (the "verb" must come first), so commands
  557. which require multiple keys (e.g. `findandmodify`)
  558. should use an instance of :class:`~bson.son.SON` or
  559. a string and kwargs instead of a Python `dict`.
  560. - `value` (optional): value to use for the command verb when
  561. `command` is passed as a string
  562. - `check` (optional): check the response for errors, raising
  563. :class:`~pymongo.errors.OperationFailure` if there are any
  564. - `allowable_errors`: if `check` is ``True``, error messages
  565. in this list will be ignored by error-checking
  566. - `read_preference` (optional): The read preference for this
  567. operation. See :mod:`~pymongo.read_preferences` for options.
  568. If the provided `session` is in a transaction, defaults to the
  569. read preference configured for the transaction.
  570. Otherwise, defaults to
  571. :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
  572. - `codec_options`: A :class:`~bson.codec_options.CodecOptions`
  573. instance.
  574. - `session` (optional): A
  575. :class:`~pymongo.client_session.ClientSession`.
  576. - `**kwargs` (optional): additional keyword arguments will
  577. be added to the command document before it is sent
  578. .. note:: :meth:`command` does **not** obey this Database's
  579. :attr:`read_preference` or :attr:`codec_options`. You must use the
  580. `read_preference` and `codec_options` parameters instead.
  581. .. note:: :meth:`command` does **not** apply any custom TypeDecoders
  582. when decoding the command response.
  583. .. note:: If this client has been configured to use MongoDB Versioned
  584. API (see :ref:`versioned-api-ref`), then :meth:`command` will
  585. automactically add API versioning options to the given command.
  586. Explicitly adding API versioning options in the command and
  587. declaring an API version on the client is not supported.
  588. .. versionchanged:: 3.6
  589. Added ``session`` parameter.
  590. .. versionchanged:: 3.0
  591. Removed the `as_class`, `fields`, `uuid_subtype`, `tag_sets`,
  592. and `secondary_acceptable_latency_ms` option.
  593. Removed `compile_re` option: PyMongo now always represents BSON
  594. regular expressions as :class:`~bson.regex.Regex` objects. Use
  595. :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
  596. BSON regular expression to a Python regular expression object.
  597. Added the `codec_options` parameter.
  598. .. versionchanged:: 2.7
  599. Added `compile_re` option. If set to False, PyMongo represented BSON
  600. regular expressions as :class:`~bson.regex.Regex` objects instead of
  601. attempting to compile BSON regular expressions as Python native
  602. regular expressions, thus preventing errors for some incompatible
  603. patterns, see `PYTHON-500`_.
  604. .. versionchanged:: 2.3
  605. Added `tag_sets` and `secondary_acceptable_latency_ms` options.
  606. .. versionchanged:: 2.2
  607. Added support for `as_class` - the class you want to use for
  608. the resulting documents
  609. .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
  610. .. mongodoc:: commands
  611. """
  612. if read_preference is None:
  613. read_preference = ((session and session._txn_read_preference())
  614. or ReadPreference.PRIMARY)
  615. with self.__client._socket_for_reads(
  616. read_preference, session) as (sock_info, secondary_ok):
  617. return self._command(sock_info, command, secondary_ok, value,
  618. check, allowable_errors, read_preference,
  619. codec_options, session=session, **kwargs)
  620. def _retryable_read_command(self, command, value=1, check=True,
  621. allowable_errors=None, read_preference=None,
  622. codec_options=DEFAULT_CODEC_OPTIONS, session=None, **kwargs):
  623. """Same as command but used for retryable read commands."""
  624. if read_preference is None:
  625. read_preference = ((session and session._txn_read_preference())
  626. or ReadPreference.PRIMARY)
  627. def _cmd(session, server, sock_info, secondary_ok):
  628. return self._command(sock_info, command, secondary_ok, value,
  629. check, allowable_errors, read_preference,
  630. codec_options, session=session, **kwargs)
  631. return self.__client._retryable_read(
  632. _cmd, read_preference, session)
  633. def _list_collections(self, sock_info, secondary_okay, session,
  634. read_preference, **kwargs):
  635. """Internal listCollections helper."""
  636. coll = self.get_collection(
  637. "$cmd", read_preference=read_preference)
  638. if sock_info.max_wire_version > 2:
  639. cmd = SON([("listCollections", 1),
  640. ("cursor", {})])
  641. cmd.update(kwargs)
  642. with self.__client._tmp_session(
  643. session, close=False) as tmp_session:
  644. cursor = self._command(
  645. sock_info, cmd, secondary_okay,
  646. read_preference=read_preference,
  647. session=tmp_session)["cursor"]
  648. cmd_cursor = CommandCursor(
  649. coll,
  650. cursor,
  651. sock_info.address,
  652. session=tmp_session,
  653. explicit_session=session is not None)
  654. else:
  655. match = _INDEX_REGEX
  656. if "filter" in kwargs:
  657. match = {"$and": [_INDEX_REGEX, kwargs["filter"]]}
  658. dblen = len(self.name.encode("utf8") + b".")
  659. pipeline = [
  660. {"$project": {"name": {"$substr": ["$name", dblen, -1]},
  661. "options": 1}},
  662. {"$match": match}
  663. ]
  664. cmd = SON([("aggregate", "system.namespaces"),
  665. ("pipeline", pipeline),
  666. ("cursor", kwargs.get("cursor", {}))])
  667. cursor = self._command(sock_info, cmd, secondary_okay)["cursor"]
  668. cmd_cursor = CommandCursor(coll, cursor, sock_info.address)
  669. cmd_cursor._maybe_pin_connection(sock_info)
  670. return cmd_cursor
  671. def list_collections(self, session=None, filter=None, **kwargs):
  672. """Get a cursor over the collections of this database.
  673. :Parameters:
  674. - `session` (optional): a
  675. :class:`~pymongo.client_session.ClientSession`.
  676. - `filter` (optional): A query document to filter the list of
  677. collections returned from the listCollections command.
  678. - `**kwargs` (optional): Optional parameters of the
  679. `listCollections command
  680. <https://docs.mongodb.com/manual/reference/command/listCollections/>`_
  681. can be passed as keyword arguments to this method. The supported
  682. options differ by server version.
  683. :Returns:
  684. An instance of :class:`~pymongo.command_cursor.CommandCursor`.
  685. .. versionadded:: 3.6
  686. """
  687. if filter is not None:
  688. kwargs['filter'] = filter
  689. read_pref = ((session and session._txn_read_preference())
  690. or ReadPreference.PRIMARY)
  691. def _cmd(session, server, sock_info, secondary_okay):
  692. return self._list_collections(
  693. sock_info, secondary_okay, session, read_preference=read_pref,
  694. **kwargs)
  695. return self.__client._retryable_read(
  696. _cmd, read_pref, session)
  697. def list_collection_names(self, session=None, filter=None, **kwargs):
  698. """Get a list of all the collection names in this database.
  699. For example, to list all non-system collections::
  700. filter = {"name": {"$regex": r"^(?!system\\.)"}}
  701. db.list_collection_names(filter=filter)
  702. :Parameters:
  703. - `session` (optional): a
  704. :class:`~pymongo.client_session.ClientSession`.
  705. - `filter` (optional): A query document to filter the list of
  706. collections returned from the listCollections command.
  707. - `**kwargs` (optional): Optional parameters of the
  708. `listCollections command
  709. <https://docs.mongodb.com/manual/reference/command/listCollections/>`_
  710. can be passed as keyword arguments to this method. The supported
  711. options differ by server version.
  712. .. versionchanged:: 3.8
  713. Added the ``filter`` and ``**kwargs`` parameters.
  714. .. versionadded:: 3.6
  715. """
  716. if filter is None:
  717. kwargs["nameOnly"] = True
  718. else:
  719. # The enumerate collections spec states that "drivers MUST NOT set
  720. # nameOnly if a filter specifies any keys other than name."
  721. common.validate_is_mapping("filter", filter)
  722. kwargs["filter"] = filter
  723. if not filter or (len(filter) == 1 and "name" in filter):
  724. kwargs["nameOnly"] = True
  725. return [result["name"]
  726. for result in self.list_collections(session=session, **kwargs)]
  727. def collection_names(self, include_system_collections=True,
  728. session=None):
  729. """**DEPRECATED**: Get a list of all the collection names in this
  730. database.
  731. :Parameters:
  732. - `include_system_collections` (optional): if ``False`` list
  733. will not include system collections (e.g ``system.indexes``)
  734. - `session` (optional): a
  735. :class:`~pymongo.client_session.ClientSession`.
  736. .. versionchanged:: 3.7
  737. Deprecated. Use :meth:`list_collection_names` instead.
  738. .. versionchanged:: 3.6
  739. Added ``session`` parameter.
  740. """
  741. warnings.warn("collection_names is deprecated. Use "
  742. "list_collection_names instead.",
  743. DeprecationWarning, stacklevel=2)
  744. kws = {} if include_system_collections else _SYSTEM_FILTER
  745. return [result["name"]
  746. for result in self.list_collections(session=session,
  747. nameOnly=True, **kws)]
  748. def drop_collection(self, name_or_collection, session=None):
  749. """Drop a collection.
  750. :Parameters:
  751. - `name_or_collection`: the name of a collection to drop or the
  752. collection object itself
  753. - `session` (optional): a
  754. :class:`~pymongo.client_session.ClientSession`.
  755. .. note:: The :attr:`~pymongo.database.Database.write_concern` of
  756. this database is automatically applied to this operation when using
  757. MongoDB >= 3.4.
  758. .. versionchanged:: 3.6
  759. Added ``session`` parameter.
  760. .. versionchanged:: 3.4
  761. Apply this database's write concern automatically to this operation
  762. when connected to MongoDB >= 3.4.
  763. """
  764. name = name_or_collection
  765. if isinstance(name, Collection):
  766. name = name.name
  767. if not isinstance(name, string_type):
  768. raise TypeError("name_or_collection must be an "
  769. "instance of %s" % (string_type.__name__,))
  770. self.__client._purge_index(self.__name, name)
  771. with self.__client._socket_for_writes(session) as sock_info:
  772. return self._command(
  773. sock_info, 'drop', value=_unicode(name),
  774. allowable_errors=['ns not found', 26],
  775. write_concern=self._write_concern_for(session),
  776. parse_write_concern_error=True,
  777. session=session)
  778. def validate_collection(self, name_or_collection,
  779. scandata=False, full=False, session=None,
  780. background=None):
  781. """Validate a collection.
  782. Returns a dict of validation info. Raises CollectionInvalid if
  783. validation fails.
  784. See also the MongoDB documentation on the `validate command`_.
  785. :Parameters:
  786. - `name_or_collection`: A Collection object or the name of a
  787. collection to validate.
  788. - `scandata`: Do extra checks beyond checking the overall
  789. structure of the collection.
  790. - `full`: Have the server do a more thorough scan of the
  791. collection. Use with `scandata` for a thorough scan
  792. of the structure of the collection and the individual
  793. documents.
  794. - `session` (optional): a
  795. :class:`~pymongo.client_session.ClientSession`.
  796. - `background` (optional): A boolean flag that determines whether
  797. the command runs in the background. Requires MongoDB 4.4+.
  798. .. versionchanged:: 3.11
  799. Added ``background`` parameter.
  800. .. versionchanged:: 3.6
  801. Added ``session`` parameter.
  802. .. _validate command: https://docs.mongodb.com/manual/reference/command/validate/
  803. """
  804. name = name_or_collection
  805. if isinstance(name, Collection):
  806. name = name.name
  807. if not isinstance(name, string_type):
  808. raise TypeError("name_or_collection must be an instance of "
  809. "%s or Collection" % (string_type.__name__,))
  810. cmd = SON([("validate", _unicode(name)),
  811. ("scandata", scandata),
  812. ("full", full)])
  813. if background is not None:
  814. cmd["background"] = background
  815. result = self.command(cmd, session=session)
  816. valid = True
  817. # Pre 1.9 results
  818. if "result" in result:
  819. info = result["result"]
  820. if info.find("exception") != -1 or info.find("corrupt") != -1:
  821. raise CollectionInvalid("%s invalid: %s" % (name, info))
  822. # Sharded results
  823. elif "raw" in result:
  824. for _, res in iteritems(result["raw"]):
  825. if "result" in res:
  826. info = res["result"]
  827. if (info.find("exception") != -1 or
  828. info.find("corrupt") != -1):
  829. raise CollectionInvalid("%s invalid: "
  830. "%s" % (name, info))
  831. elif not res.get("valid", False):
  832. valid = False
  833. break
  834. # Post 1.9 non-sharded results.
  835. elif not result.get("valid", False):
  836. valid = False
  837. if not valid:
  838. raise CollectionInvalid("%s invalid: %r" % (name, result))
  839. return result
  840. def _current_op(self, include_all=False, session=None):
  841. """Helper for running $currentOp."""
  842. cmd = SON([("currentOp", 1), ("$all", include_all)])
  843. with self.__client._socket_for_writes(session) as sock_info:
  844. if sock_info.max_wire_version >= 4:
  845. return self.__client.admin._command(
  846. sock_info, cmd, codec_options=self.codec_options,
  847. session=session)
  848. else:
  849. spec = {"$all": True} if include_all else {}
  850. return _first_batch(sock_info, "admin", "$cmd.sys.inprog",
  851. spec, -1, True, self.codec_options,
  852. ReadPreference.PRIMARY, cmd,
  853. self.client._event_listeners)
  854. def current_op(self, include_all=False, session=None):
  855. """**DEPRECATED**: Get information on operations currently running.
  856. Starting with MongoDB 3.6 this helper is obsolete. The functionality
  857. provided by this helper is available in MongoDB 3.6+ using the
  858. `$currentOp aggregation pipeline stage`_, which can be used with
  859. :meth:`aggregate`. Note that, while this helper can only return
  860. a single document limited to a 16MB result, :meth:`aggregate`
  861. returns a cursor avoiding that limitation.
  862. Users of MongoDB versions older than 3.6 can use the `currentOp command`_
  863. directly::
  864. # MongoDB 3.2 and 3.4
  865. client.admin.command("currentOp")
  866. Or query the "inprog" virtual collection::
  867. # MongoDB 2.6 and 3.0
  868. client.admin["$cmd.sys.inprog"].find_one()
  869. :Parameters:
  870. - `include_all` (optional): if ``True`` also list currently
  871. idle operations in the result
  872. - `session` (optional): a
  873. :class:`~pymongo.client_session.ClientSession`.
  874. .. versionchanged:: 3.9
  875. Deprecated.
  876. .. versionchanged:: 3.6
  877. Added ``session`` parameter.
  878. .. _$currentOp aggregation pipeline stage: https://docs.mongodb.com/manual/reference/operator/aggregation/currentOp/
  879. .. _currentOp command: https://docs.mongodb.com/manual/reference/command/currentOp/
  880. """
  881. warnings.warn("current_op() is deprecated. See the documentation for "
  882. "more information",
  883. DeprecationWarning, stacklevel=2)
  884. return self._current_op(include_all, session)
  885. def profiling_level(self, session=None):
  886. """**DEPRECATED**: Get the database's current profiling level.
  887. Starting with PyMongo 3.12, this helper is obsolete. Instead, users
  888. can run the `profile command`_, using the :meth:`command`
  889. helper to get the current profiler level. Running the
  890. `profile command`_ with the level set to ``-1`` returns the current
  891. profiler information without changing it::
  892. res = db.command("profile", -1)
  893. profiling_level = res["was"]
  894. The format of ``res`` depends on the version of MongoDB in use.
  895. Returns one of (:data:`~pymongo.OFF`,
  896. :data:`~pymongo.SLOW_ONLY`, :data:`~pymongo.ALL`).
  897. :Parameters:
  898. - `session` (optional): a
  899. :class:`~pymongo.client_session.ClientSession`.
  900. .. versionchanged:: 3.12
  901. Deprecated.
  902. .. versionchanged:: 3.6
  903. Added ``session`` parameter.
  904. .. mongodoc:: profiling
  905. .. _profile command: https://docs.mongodb.com/manual/reference/command/profile/
  906. """
  907. warnings.warn("profiling_level() is deprecated. See the documentation "
  908. "for more information",
  909. DeprecationWarning, stacklevel=2)
  910. result = self.command("profile", -1, session=session)
  911. assert result["was"] >= 0 and result["was"] <= 2
  912. return result["was"]
  913. def set_profiling_level(self, level, slow_ms=None, session=None,
  914. sample_rate=None, filter=None):
  915. """**DEPRECATED**: Set the database's profiling level.
  916. Starting with PyMongo 3.12, this helper is obsolete. Instead, users
  917. can directly run the `profile command`_, using the :meth:`command`
  918. helper, e.g.::
  919. res = db.command("profile", 2, filter={"op": "query"})
  920. :Parameters:
  921. - `level`: Specifies a profiling level, see list of possible values
  922. below.
  923. - `slow_ms`: Optionally modify the threshold for the profile to
  924. consider a query or operation. Even if the profiler is off queries
  925. slower than the `slow_ms` level will get written to the logs.
  926. - `session` (optional): a
  927. :class:`~pymongo.client_session.ClientSession`.
  928. - `sample_rate` (optional): The fraction of slow operations that
  929. should be profiled or logged expressed as a float between 0 and 1.
  930. - `filter` (optional): A filter expression that controls which
  931. operations are profiled and logged.
  932. Possible `level` values:
  933. +----------------------------+------------------------------------+
  934. | Level | Setting |
  935. +============================+====================================+
  936. | :data:`~pymongo.OFF` | Off. No profiling. |
  937. +----------------------------+------------------------------------+
  938. | :data:`~pymongo.SLOW_ONLY` | On. Only includes slow operations. |
  939. +----------------------------+------------------------------------+
  940. | :data:`~pymongo.ALL` | On. Includes all operations. |
  941. +----------------------------+------------------------------------+
  942. Raises :class:`ValueError` if level is not one of
  943. (:data:`~pymongo.OFF`, :data:`~pymongo.SLOW_ONLY`,
  944. :data:`~pymongo.ALL`).
  945. .. versionchanged:: 3.12
  946. Added the ``sample_rate`` and ``filter`` parameters.
  947. Deprecated.
  948. .. versionchanged:: 3.6
  949. Added ``session`` parameter.
  950. .. mongodoc:: profiling
  951. .. _profile command: https://docs.mongodb.com/manual/reference/command/profile/
  952. """
  953. warnings.warn("set_profiling_level() is deprecated. See the "
  954. "documentation for more information",
  955. DeprecationWarning, stacklevel=2)
  956. if not isinstance(level, int) or level < 0 or level > 2:
  957. raise ValueError("level must be one of (OFF, SLOW_ONLY, ALL)")
  958. if slow_ms is not None and not isinstance(slow_ms, int):
  959. raise TypeError("slow_ms must be an integer")
  960. if sample_rate is not None and not isinstance(sample_rate, float):
  961. raise TypeError(
  962. "sample_rate must be a float, not %r" % (sample_rate,))
  963. cmd = SON(profile=level)
  964. if slow_ms is not None:
  965. cmd['slowms'] = slow_ms
  966. if sample_rate is not None:
  967. cmd['sampleRate'] = sample_rate
  968. if filter is not None:
  969. cmd['filter'] = filter
  970. self.command(cmd, session=session)
  971. def profiling_info(self, session=None):
  972. """**DEPRECATED**: Returns a list containing current profiling
  973. information.
  974. Starting with PyMongo 3.12, this helper is obsolete. Instead, users
  975. can view the database profiler output by running
  976. :meth:`~pymongo.collection.Collection.find` against the
  977. ``system.profile`` collection as detailed in the `profiler output`_
  978. documentation::
  979. profiling_info = list(db["system.profile"].find())
  980. :Parameters:
  981. - `session` (optional): a
  982. :class:`~pymongo.client_session.ClientSession`.
  983. .. versionchanged:: 3.12
  984. Deprecated.
  985. .. versionchanged:: 3.6
  986. Added ``session`` parameter.
  987. .. mongodoc:: profiling
  988. .. _profiler output: https://docs.mongodb.com/manual/reference/database-profiler/
  989. """
  990. warnings.warn("profiling_info() is deprecated. See the "
  991. "documentation for more information",
  992. DeprecationWarning, stacklevel=2)
  993. return list(self["system.profile"].find(session=session))
  994. def error(self):
  995. """**DEPRECATED**: Get the error if one occurred on the last operation.
  996. This method is obsolete: all MongoDB write operations (insert, update,
  997. remove, and so on) use the write concern ``w=1`` and report their
  998. errors by default.
  999. .. versionchanged:: 2.8
  1000. Deprecated.
  1001. """
  1002. warnings.warn("Database.error() is deprecated",
  1003. DeprecationWarning, stacklevel=2)
  1004. error = self.command("getlasterror")
  1005. error_msg = error.get("err", "")
  1006. if error_msg is None:
  1007. return None
  1008. if error_msg.startswith(HelloCompat.LEGACY_ERROR):
  1009. # Reset primary server and request check, if another thread isn't
  1010. # doing so already.
  1011. primary = self.__client.primary
  1012. if primary:
  1013. self.__client._handle_getlasterror(primary, error_msg)
  1014. return error
  1015. def last_status(self):
  1016. """**DEPRECATED**: Get status information from the last operation.
  1017. This method is obsolete: all MongoDB write operations (insert, update,
  1018. remove, and so on) use the write concern ``w=1`` and report their
  1019. errors by default.
  1020. Returns a SON object with status information.
  1021. .. versionchanged:: 2.8
  1022. Deprecated.
  1023. """
  1024. warnings.warn("last_status() is deprecated",
  1025. DeprecationWarning, stacklevel=2)
  1026. return self.command("getlasterror")
  1027. def previous_error(self):
  1028. """**DEPRECATED**: Get the most recent error on this database.
  1029. This method is obsolete: all MongoDB write operations (insert, update,
  1030. remove, and so on) use the write concern ``w=1`` and report their
  1031. errors by default.
  1032. Only returns errors that have occurred since the last call to
  1033. :meth:`reset_error_history`. Returns None if no such errors have
  1034. occurred.
  1035. .. versionchanged:: 2.8
  1036. Deprecated.
  1037. """
  1038. warnings.warn("previous_error() is deprecated",
  1039. DeprecationWarning, stacklevel=2)
  1040. error = self.command("getpreverror")
  1041. if error.get("err", 0) is None:
  1042. return None
  1043. return error
  1044. def reset_error_history(self):
  1045. """**DEPRECATED**: Reset the error history of this database.
  1046. This method is obsolete: all MongoDB write operations (insert, update,
  1047. remove, and so on) use the write concern ``w=1`` and report their
  1048. errors by default.
  1049. Calls to :meth:`previous_error` will only return errors that have
  1050. occurred since the most recent call to this method.
  1051. .. versionchanged:: 2.8
  1052. Deprecated.
  1053. """
  1054. warnings.warn("reset_error_history() is deprecated",
  1055. DeprecationWarning, stacklevel=2)
  1056. self.command("reseterror")
  1057. def __iter__(self):
  1058. return self
  1059. def __next__(self):
  1060. raise TypeError("'Database' object is not iterable")
  1061. next = __next__
  1062. def _default_role(self, read_only):
  1063. """Return the default user role for this database."""
  1064. if self.name == "admin":
  1065. if read_only:
  1066. return "readAnyDatabase"
  1067. else:
  1068. return "root"
  1069. else:
  1070. if read_only:
  1071. return "read"
  1072. else:
  1073. return "dbOwner"
  1074. def _create_or_update_user(
  1075. self, create, name, password, read_only, session=None, **kwargs):
  1076. """Use a command to create (if create=True) or modify a user.
  1077. """
  1078. opts = {}
  1079. if read_only or (create and "roles" not in kwargs):
  1080. warnings.warn("Creating a user with the read_only option "
  1081. "or without roles is deprecated in MongoDB "
  1082. ">= 2.6", DeprecationWarning)
  1083. opts["roles"] = [self._default_role(read_only)]
  1084. if read_only:
  1085. warnings.warn("The read_only option is deprecated in MongoDB "
  1086. ">= 2.6, use 'roles' instead", DeprecationWarning)
  1087. if password is not None:
  1088. if "digestPassword" in kwargs:
  1089. raise ConfigurationError("The digestPassword option is not "
  1090. "supported via add_user. Please use "
  1091. "db.command('createUser', ...) "
  1092. "instead for this option.")
  1093. opts["pwd"] = password
  1094. # Don't send {} as writeConcern.
  1095. if self.write_concern.acknowledged and self.write_concern.document:
  1096. opts["writeConcern"] = self.write_concern.document
  1097. opts.update(kwargs)
  1098. if create:
  1099. command_name = "createUser"
  1100. else:
  1101. command_name = "updateUser"
  1102. self.command(command_name, name, session=session, **opts)
  1103. def add_user(self, name, password=None, read_only=None, session=None,
  1104. **kwargs):
  1105. """**DEPRECATED**: Create user `name` with password `password`.
  1106. Add a new user with permissions for this :class:`Database`.
  1107. .. note:: Will change the password if user `name` already exists.
  1108. .. note:: add_user is deprecated and will be removed in PyMongo
  1109. 4.0. Starting with MongoDB 2.6 user management is handled with four
  1110. database commands, createUser_, usersInfo_, updateUser_, and
  1111. dropUser_.
  1112. To create a user::
  1113. db.command("createUser", "admin", pwd="password", roles=["root"])
  1114. To create a read-only user::
  1115. db.command("createUser", "user", pwd="password", roles=["read"])
  1116. To change a password::
  1117. db.command("updateUser", "user", pwd="newpassword")
  1118. Or change roles::
  1119. db.command("updateUser", "user", roles=["readWrite"])
  1120. .. _createUser: https://docs.mongodb.com/manual/reference/command/createUser/
  1121. .. _usersInfo: https://docs.mongodb.com/manual/reference/command/usersInfo/
  1122. .. _updateUser: https://docs.mongodb.com/manual/reference/command/updateUser/
  1123. .. _dropUser: https://docs.mongodb.com/manual/reference/command/createUser/
  1124. .. warning:: Never create or modify users over an insecure network without
  1125. the use of TLS. See :doc:`/examples/tls` for more information.
  1126. :Parameters:
  1127. - `name`: the name of the user to create
  1128. - `password` (optional): the password of the user to create. Can not
  1129. be used with the ``userSource`` argument.
  1130. - `read_only` (optional): if ``True`` the user will be read only
  1131. - `**kwargs` (optional): optional fields for the user document
  1132. (e.g. ``userSource``, ``otherDBRoles``, or ``roles``). See
  1133. `<http://docs.mongodb.org/manual/reference/privilege-documents>`_
  1134. for more information.
  1135. - `session` (optional): a
  1136. :class:`~pymongo.client_session.ClientSession`.
  1137. .. versionchanged:: 3.7
  1138. Added support for SCRAM-SHA-256 users with MongoDB 4.0 and later.
  1139. .. versionchanged:: 3.6
  1140. Added ``session`` parameter. Deprecated add_user.
  1141. .. versionchanged:: 2.5
  1142. Added kwargs support for optional fields introduced in MongoDB 2.4
  1143. .. versionchanged:: 2.2
  1144. Added support for read only users
  1145. """
  1146. warnings.warn("add_user is deprecated and will be removed in PyMongo "
  1147. "4.0. Use db.command with createUser or updateUser "
  1148. "instead", DeprecationWarning, stacklevel=2)
  1149. if not isinstance(name, string_type):
  1150. raise TypeError("name must be an "
  1151. "instance of %s" % (string_type.__name__,))
  1152. if password is not None:
  1153. if not isinstance(password, string_type):
  1154. raise TypeError("password must be an "
  1155. "instance of %s" % (string_type.__name__,))
  1156. if len(password) == 0:
  1157. raise ValueError("password can't be empty")
  1158. if read_only is not None:
  1159. read_only = common.validate_boolean('read_only', read_only)
  1160. if 'roles' in kwargs:
  1161. raise ConfigurationError("Can not use "
  1162. "read_only and roles together")
  1163. try:
  1164. uinfo = self.command("usersInfo", name, session=session)
  1165. # Create the user if not found in uinfo, otherwise update one.
  1166. self._create_or_update_user(
  1167. (not uinfo["users"]), name, password, read_only,
  1168. session=session, **kwargs)
  1169. except OperationFailure as exc:
  1170. # Unauthorized. Attempt to create the user in case of
  1171. # localhost exception.
  1172. if exc.code == 13:
  1173. self._create_or_update_user(
  1174. True, name, password, read_only, session=session, **kwargs)
  1175. else:
  1176. raise
  1177. def remove_user(self, name, session=None):
  1178. """**DEPRECATED**: Remove user `name` from this :class:`Database`.
  1179. User `name` will no longer have permissions to access this
  1180. :class:`Database`.
  1181. .. note:: remove_user is deprecated and will be removed in PyMongo
  1182. 4.0. Use the dropUser command instead::
  1183. db.command("dropUser", "user")
  1184. :Parameters:
  1185. - `name`: the name of the user to remove
  1186. - `session` (optional): a
  1187. :class:`~pymongo.client_session.ClientSession`.
  1188. .. versionchanged:: 3.6
  1189. Added ``session`` parameter. Deprecated remove_user.
  1190. """
  1191. warnings.warn("remove_user is deprecated and will be removed in "
  1192. "PyMongo 4.0. Use db.command with dropUser "
  1193. "instead", DeprecationWarning, stacklevel=2)
  1194. cmd = SON([("dropUser", name)])
  1195. # Don't send {} as writeConcern.
  1196. if self.write_concern.acknowledged and self.write_concern.document:
  1197. cmd["writeConcern"] = self.write_concern.document
  1198. self.command(cmd, session=session)
  1199. def authenticate(self, name=None, password=None,
  1200. source=None, mechanism='DEFAULT', **kwargs):
  1201. """**DEPRECATED**: Authenticate to use this database.
  1202. .. warning:: Starting in MongoDB 3.6, calling :meth:`authenticate`
  1203. invalidates all existing cursors. It may also leave logical sessions
  1204. open on the server for up to 30 minutes until they time out.
  1205. Authentication lasts for the life of the underlying client
  1206. instance, or until :meth:`logout` is called.
  1207. Raises :class:`TypeError` if (required) `name`, (optional) `password`,
  1208. or (optional) `source` is not an instance of :class:`basestring`
  1209. (:class:`str` in python 3).
  1210. .. note::
  1211. - This method authenticates the current connection, and
  1212. will also cause all new :class:`~socket.socket` connections
  1213. in the underlying client instance to be authenticated automatically.
  1214. - Authenticating more than once on the same database with different
  1215. credentials is not supported. You must call :meth:`logout` before
  1216. authenticating with new credentials.
  1217. - When sharing a client instance between multiple threads, all
  1218. threads will share the authentication. If you need different
  1219. authentication profiles for different purposes you must use
  1220. distinct client instances.
  1221. :Parameters:
  1222. - `name`: the name of the user to authenticate. Optional when
  1223. `mechanism` is MONGODB-X509 and the MongoDB server version is
  1224. >= 3.4.
  1225. - `password` (optional): the password of the user to authenticate.
  1226. Not used with GSSAPI or MONGODB-X509 authentication.
  1227. - `source` (optional): the database to authenticate on. If not
  1228. specified the current database is used.
  1229. - `mechanism` (optional): See :data:`~pymongo.auth.MECHANISMS` for
  1230. options. If no mechanism is specified, PyMongo automatically uses
  1231. MONGODB-CR when connected to a pre-3.0 version of MongoDB,
  1232. SCRAM-SHA-1 when connected to MongoDB 3.0 through 3.6, and
  1233. negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) when
  1234. connected to MongoDB 4.0+.
  1235. - `authMechanismProperties` (optional): Used to specify
  1236. authentication mechanism specific options. To specify the service
  1237. name for GSSAPI authentication pass
  1238. ``authMechanismProperties='SERVICE_NAME:<service name>'``.
  1239. To specify the session token for MONGODB-AWS authentication pass
  1240. ``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.
  1241. .. versionchanged:: 3.7
  1242. Added support for SCRAM-SHA-256 with MongoDB 4.0 and later.
  1243. .. versionchanged:: 3.5
  1244. Deprecated. Authenticating multiple users conflicts with support for
  1245. logical sessions in MongoDB 3.6. To authenticate as multiple users,
  1246. create multiple instances of MongoClient.
  1247. .. versionadded:: 2.8
  1248. Use SCRAM-SHA-1 with MongoDB 3.0 and later.
  1249. .. versionchanged:: 2.5
  1250. Added the `source` and `mechanism` parameters. :meth:`authenticate`
  1251. now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
  1252. authentication fails due to invalid credentials or configuration
  1253. issues.
  1254. .. mongodoc:: authenticate
  1255. """
  1256. if name is not None and not isinstance(name, string_type):
  1257. raise TypeError("name must be an "
  1258. "instance of %s" % (string_type.__name__,))
  1259. if password is not None and not isinstance(password, string_type):
  1260. raise TypeError("password must be an "
  1261. "instance of %s" % (string_type.__name__,))
  1262. if source is not None and not isinstance(source, string_type):
  1263. raise TypeError("source must be an "
  1264. "instance of %s" % (string_type.__name__,))
  1265. common.validate_auth_mechanism('mechanism', mechanism)
  1266. validated_options = common._CaseInsensitiveDictionary()
  1267. for option, value in iteritems(kwargs):
  1268. normalized, val = common.validate_auth_option(option, value)
  1269. validated_options[normalized] = val
  1270. credentials = auth._build_credentials_tuple(
  1271. mechanism,
  1272. source,
  1273. name,
  1274. password,
  1275. validated_options,
  1276. self.name)
  1277. self.client._cache_credentials(
  1278. self.name,
  1279. credentials,
  1280. connect=True)
  1281. return True
  1282. def logout(self):
  1283. """**DEPRECATED**: Deauthorize use of this database.
  1284. .. warning:: Starting in MongoDB 3.6, calling :meth:`logout`
  1285. invalidates all existing cursors. It may also leave logical sessions
  1286. open on the server for up to 30 minutes until they time out.
  1287. """
  1288. warnings.warn("Database.logout() is deprecated",
  1289. DeprecationWarning, stacklevel=2)
  1290. # Sockets will be deauthenticated as they are used.
  1291. self.client._purge_credentials(self.name)
  1292. def dereference(self, dbref, session=None, **kwargs):
  1293. """Dereference a :class:`~bson.dbref.DBRef`, getting the
  1294. document it points to.
  1295. Raises :class:`TypeError` if `dbref` is not an instance of
  1296. :class:`~bson.dbref.DBRef`. Returns a document, or ``None`` if
  1297. the reference does not point to a valid document. Raises
  1298. :class:`ValueError` if `dbref` has a database specified that
  1299. is different from the current database.
  1300. :Parameters:
  1301. - `dbref`: the reference
  1302. - `session` (optional): a
  1303. :class:`~pymongo.client_session.ClientSession`.
  1304. - `**kwargs` (optional): any additional keyword arguments
  1305. are the same as the arguments to
  1306. :meth:`~pymongo.collection.Collection.find`.
  1307. .. versionchanged:: 3.6
  1308. Added ``session`` parameter.
  1309. """
  1310. if not isinstance(dbref, DBRef):
  1311. raise TypeError("cannot dereference a %s" % type(dbref))
  1312. if dbref.database is not None and dbref.database != self.__name:
  1313. raise ValueError("trying to dereference a DBRef that points to "
  1314. "another database (%r not %r)" % (dbref.database,
  1315. self.__name))
  1316. return self[dbref.collection].find_one(
  1317. {"_id": dbref.id}, session=session, **kwargs)
  1318. def eval(self, code, *args):
  1319. """**DEPRECATED**: Evaluate a JavaScript expression in MongoDB.
  1320. :Parameters:
  1321. - `code`: string representation of JavaScript code to be
  1322. evaluated
  1323. - `args` (optional): additional positional arguments are
  1324. passed to the `code` being evaluated
  1325. .. warning:: the eval command is deprecated in MongoDB 3.0 and
  1326. will be removed in a future server version.
  1327. """
  1328. warnings.warn("Database.eval() is deprecated",
  1329. DeprecationWarning, stacklevel=2)
  1330. if not isinstance(code, Code):
  1331. code = Code(code)
  1332. result = self.command("$eval", code, args=args)
  1333. return result.get("retval", None)
  1334. def __call__(self, *args, **kwargs):
  1335. """This is only here so that some API misusages are easier to debug.
  1336. """
  1337. raise TypeError("'Database' object is not callable. If you meant to "
  1338. "call the '%s' method on a '%s' object it is "
  1339. "failing because no such method exists." % (
  1340. self.__name, self.__client.__class__.__name__))
  1341. class SystemJS(object):
  1342. """**DEPRECATED**: Helper class for dealing with stored JavaScript.
  1343. """
  1344. def __init__(self, database):
  1345. """**DEPRECATED**: Get a system js helper for the database `database`.
  1346. SystemJS will be removed in PyMongo 4.0.
  1347. """
  1348. warnings.warn("SystemJS is deprecated",
  1349. DeprecationWarning, stacklevel=2)
  1350. if not database.write_concern.acknowledged:
  1351. database = database.client.get_database(
  1352. database.name, write_concern=DEFAULT_WRITE_CONCERN)
  1353. # can't just assign it since we've overridden __setattr__
  1354. object.__setattr__(self, "_db", database)
  1355. def __setattr__(self, name, code):
  1356. self._db.system.js.replace_one(
  1357. {"_id": name}, {"_id": name, "value": Code(code)}, True)
  1358. def __setitem__(self, name, code):
  1359. self.__setattr__(name, code)
  1360. def __delattr__(self, name):
  1361. self._db.system.js.delete_one({"_id": name})
  1362. def __delitem__(self, name):
  1363. self.__delattr__(name)
  1364. def __getattr__(self, name):
  1365. return lambda *args: self._db.eval(Code("function() { "
  1366. "return this[name].apply("
  1367. "this, arguments); }",
  1368. scope={'name': name}), *args)
  1369. def __getitem__(self, name):
  1370. return self.__getattr__(name)
  1371. def list(self):
  1372. """Get a list of the names of the functions stored in this database."""
  1373. return [x["_id"] for x in self._db.system.js.find(projection=["_id"])]