collection.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. # Copyright 2009-2015 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. """Collection level utilities for Mongo."""
  15. import collections
  16. import warnings
  17. from bson.code import Code
  18. from bson.objectid import ObjectId
  19. from bson.py3compat import (_unicode,
  20. integer_types,
  21. string_type,
  22. u)
  23. from bson.codec_options import CodecOptions
  24. from bson.son import SON
  25. from pymongo import (common,
  26. helpers,
  27. message)
  28. from pymongo.bulk import BulkOperationBuilder, _Bulk
  29. from pymongo.command_cursor import CommandCursor
  30. from pymongo.cursor import Cursor
  31. from pymongo.errors import ConfigurationError, InvalidName, OperationFailure
  32. from pymongo.helpers import _check_write_command_response
  33. from pymongo.message import _INSERT, _UPDATE, _DELETE
  34. from pymongo.operations import _WriteOp, IndexModel
  35. from pymongo.read_preferences import ReadPreference
  36. from pymongo.results import (BulkWriteResult,
  37. DeleteResult,
  38. InsertOneResult,
  39. InsertManyResult,
  40. UpdateResult)
  41. from pymongo.write_concern import WriteConcern
  42. try:
  43. from collections import OrderedDict
  44. _ORDERED_TYPES = (SON, OrderedDict)
  45. except ImportError:
  46. _ORDERED_TYPES = (SON,)
  47. _NO_OBJ_ERROR = "No matching object found"
  48. _UJOIN = u("%s.%s")
  49. class ReturnDocument(object):
  50. """An enum used with
  51. :meth:`~pymongo.collection.Collection.find_one_and_replace` and
  52. :meth:`~pymongo.collection.Collection.find_one_and_update`.
  53. """
  54. BEFORE = False
  55. """Return the original document before it was updated/replaced, or
  56. ``None`` if no document matches the query.
  57. """
  58. AFTER = True
  59. """Return the updated/replaced or inserted document."""
  60. class Collection(common.BaseObject):
  61. """A Mongo collection.
  62. """
  63. def __init__(self, database, name, create=False, codec_options=None,
  64. read_preference=None, write_concern=None, **kwargs):
  65. """Get / create a Mongo collection.
  66. Raises :class:`TypeError` if `name` is not an instance of
  67. :class:`basestring` (:class:`str` in python 3). Raises
  68. :class:`~pymongo.errors.InvalidName` if `name` is not a valid
  69. collection name. Any additional keyword arguments will be used
  70. as options passed to the create command. See
  71. :meth:`~pymongo.database.Database.create_collection` for valid
  72. options.
  73. If `create` is ``True`` or additional keyword arguments are
  74. present a create command will be sent. Otherwise, a create
  75. command will not be sent and the collection will be created
  76. implicitly on first use.
  77. :Parameters:
  78. - `database`: the database to get a collection from
  79. - `name`: the name of the collection to get
  80. - `create` (optional): if ``True``, force collection
  81. creation even without options being set
  82. - `codec_options` (optional): An instance of
  83. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  84. default) database.codec_options is used.
  85. - `read_preference` (optional): The read preference to use. If
  86. ``None`` (the default) database.read_preference is used.
  87. - `write_concern` (optional): An instance of
  88. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  89. default) database.write_concern is used.
  90. - `**kwargs` (optional): additional keyword arguments will
  91. be passed as options for the create collection command
  92. .. versionchanged:: 3.0
  93. Added the codec_options, read_preference, and write_concern options.
  94. Removed the uuid_subtype attribute.
  95. :class:`~pymongo.collection.Collection` no longer returns an
  96. instance of :class:`~pymongo.collection.Collection` for attribute
  97. names with leading underscores. You must use dict-style lookups
  98. instead::
  99. collection['__my_collection__']
  100. Not:
  101. collection.__my_collection__
  102. .. versionchanged:: 2.2
  103. Removed deprecated argument: options
  104. .. versionadded:: 2.1
  105. uuid_subtype attribute
  106. .. mongodoc:: collections
  107. """
  108. super(Collection, self).__init__(
  109. codec_options or database.codec_options,
  110. read_preference or database.read_preference,
  111. write_concern or database.write_concern)
  112. if not isinstance(name, string_type):
  113. raise TypeError("name must be an instance "
  114. "of %s" % (string_type.__name__,))
  115. if not name or ".." in name:
  116. raise InvalidName("collection names cannot be empty")
  117. if "$" in name and not (name.startswith("oplog.$main") or
  118. name.startswith("$cmd")):
  119. raise InvalidName("collection names must not "
  120. "contain '$': %r" % name)
  121. if name[0] == "." or name[-1] == ".":
  122. raise InvalidName("collection names must not start "
  123. "or end with '.': %r" % name)
  124. if "\x00" in name:
  125. raise InvalidName("collection names must not contain the "
  126. "null character")
  127. self.__database = database
  128. self.__name = _unicode(name)
  129. self.__full_name = _UJOIN % (self.__database.name, self.__name)
  130. if create or kwargs:
  131. self.__create(kwargs)
  132. def _socket_for_reads(self):
  133. return self.__database.client._socket_for_reads(self.read_preference)
  134. def _socket_for_primary_reads(self):
  135. return self.__database.client._socket_for_reads(ReadPreference.PRIMARY)
  136. def _socket_for_writes(self):
  137. return self.__database.client._socket_for_writes()
  138. def _command(self, sock_info, command, slave_ok=False,
  139. read_preference=None,
  140. codec_options=None, check=True, allowable_errors=None):
  141. """Internal command helper.
  142. :Parameters:
  143. - `sock_info` - A SocketInfo instance.
  144. - `command` - The command itself, as a SON instance.
  145. - `slave_ok`: whether to set the SlaveOkay wire protocol bit.
  146. - `codec_options` (optional) - An instance of
  147. :class:`~bson.codec_options.CodecOptions`.
  148. - `check`: raise OperationFailure if there are errors
  149. - `allowable_errors`: errors to ignore if `check` is True
  150. :Returns:
  151. # todo: don't return address
  152. (result document, address of server the command was run on)
  153. """
  154. return sock_info.command(self.__database.name,
  155. command,
  156. slave_ok,
  157. read_preference or self.read_preference,
  158. codec_options or self.codec_options,
  159. check,
  160. allowable_errors)
  161. def __create(self, options):
  162. """Sends a create command with the given options.
  163. """
  164. cmd = SON([("create", self.__name)])
  165. if options:
  166. if "size" in options:
  167. options["size"] = float(options["size"])
  168. cmd.update(options)
  169. with self._socket_for_writes() as sock_info:
  170. self._command(
  171. sock_info, cmd, read_preference=ReadPreference.PRIMARY)
  172. def __getattr__(self, name):
  173. """Get a sub-collection of this collection by name.
  174. Raises InvalidName if an invalid collection name is used.
  175. :Parameters:
  176. - `name`: the name of the collection to get
  177. """
  178. if name.startswith('_'):
  179. full_name = _UJOIN % (self.__name, name)
  180. raise AttributeError(
  181. "Collection has no attribute %r. To access the %s"
  182. " collection, use database['%s']." % (
  183. name, full_name, full_name))
  184. return self.__getitem__(name)
  185. def __getitem__(self, name):
  186. return Collection(self.__database, _UJOIN % (self.__name, name))
  187. def __repr__(self):
  188. return "Collection(%r, %r)" % (self.__database, self.__name)
  189. def __eq__(self, other):
  190. if isinstance(other, Collection):
  191. return (self.__database == other.database and
  192. self.__name == other.name)
  193. return NotImplemented
  194. def __ne__(self, other):
  195. return not self == other
  196. @property
  197. def full_name(self):
  198. """The full name of this :class:`Collection`.
  199. The full name is of the form `database_name.collection_name`.
  200. """
  201. return self.__full_name
  202. @property
  203. def name(self):
  204. """The name of this :class:`Collection`."""
  205. return self.__name
  206. @property
  207. def database(self):
  208. """The :class:`~pymongo.database.Database` that this
  209. :class:`Collection` is a part of.
  210. """
  211. return self.__database
  212. def with_options(
  213. self, codec_options=None, read_preference=None, write_concern=None):
  214. """Get a clone of this collection changing the specified settings.
  215. >>> coll1.read_preference
  216. Primary()
  217. >>> from pymongo import ReadPreference
  218. >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY)
  219. >>> coll1.read_preference
  220. Primary()
  221. >>> coll2.read_preference
  222. Secondary(tag_sets=None)
  223. :Parameters:
  224. - `codec_options` (optional): An instance of
  225. :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
  226. default) the :attr:`codec_options` of this :class:`Collection`
  227. is used.
  228. - `read_preference` (optional): The read preference to use. If
  229. ``None`` (the default) the :attr:`read_preference` of this
  230. :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
  231. for options.
  232. - `write_concern` (optional): An instance of
  233. :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
  234. default) the :attr:`write_concern` of this :class:`Collection`
  235. is used.
  236. """
  237. return Collection(self.__database,
  238. self.__name,
  239. False,
  240. codec_options or self.codec_options,
  241. read_preference or self.read_preference,
  242. write_concern or self.write_concern)
  243. def initialize_unordered_bulk_op(self):
  244. """Initialize an unordered batch of write operations.
  245. Operations will be performed on the server in arbitrary order,
  246. possibly in parallel. All operations will be attempted.
  247. Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.
  248. See :ref:`unordered_bulk` for examples.
  249. .. versionadded:: 2.7
  250. """
  251. return BulkOperationBuilder(self, ordered=False)
  252. def initialize_ordered_bulk_op(self):
  253. """Initialize an ordered batch of write operations.
  254. Operations will be performed on the server serially, in the
  255. order provided. If an error occurs all remaining operations
  256. are aborted.
  257. Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.
  258. See :ref:`ordered_bulk` for examples.
  259. .. versionadded:: 2.7
  260. """
  261. return BulkOperationBuilder(self, ordered=True)
  262. def bulk_write(self, requests, ordered=True):
  263. """Send a batch of write operations to the server.
  264. Requests are passed as a list of write operation instances (
  265. :class:`~pymongo.operations.InsertOne`,
  266. :class:`~pymongo.operations.UpdateOne`,
  267. :class:`~pymongo.operations.UpdateMany`,
  268. :class:`~pymongo.operations.ReplaceOne`,
  269. :class:`~pymongo.operations.DeleteOne`, or
  270. :class:`~pymongo.operations.DeleteMany`).
  271. >>> for doc in db.test.find({}):
  272. ... print(doc)
  273. ...
  274. {u'x': 1, u'_id': ObjectId('54f62e60fba5226811f634ef')}
  275. {u'x': 1, u'_id': ObjectId('54f62e60fba5226811f634f0')}
  276. >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
  277. ...
  278. >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
  279. >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}),
  280. ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)]
  281. >>> result = db.test.bulk_write(requests)
  282. >>> result.inserted_count
  283. 1
  284. >>> result.deleted_count
  285. 1
  286. >>> result.modified_count
  287. 0
  288. >>> result.upserted_ids
  289. {2: ObjectId('54f62ee28891e756a6e1abd5')}
  290. >>> for doc in db.test.find({}):
  291. ... print(doc)
  292. ...
  293. {u'x': 1, u'_id': ObjectId('54f62e60fba5226811f634f0')}
  294. {u'y': 1, u'_id': ObjectId('54f62ee2fba5226811f634f1')}
  295. {u'z': 1, u'_id': ObjectId('54f62ee28891e756a6e1abd5')}
  296. :Parameters:
  297. - `requests`: A list of write operations (see examples above).
  298. - `ordered` (optional): If ``True`` (the default) requests will be
  299. performed on the server serially, in the order provided. If an error
  300. occurs all remaining operations are aborted. If ``False`` requests
  301. will be performed on the server in arbitrary order, possibly in
  302. parallel, and all operations will be attempted.
  303. :Returns:
  304. An instance of :class:`~pymongo.results.BulkWriteResult`.
  305. .. versionadded:: 3.0
  306. """
  307. if not isinstance(requests, list):
  308. raise TypeError("requests must be a list")
  309. blk = _Bulk(self, ordered)
  310. for request in requests:
  311. if not isinstance(request, _WriteOp):
  312. raise TypeError("%r is not a valid request" % (request,))
  313. request._add_to_bulk(blk)
  314. bulk_api_result = blk.execute(self.write_concern.document)
  315. if bulk_api_result is not None:
  316. return BulkWriteResult(bulk_api_result, True)
  317. return BulkWriteResult({}, False)
  318. def _insert(self, sock_info, docs, ordered=True,
  319. check_keys=True, manipulate=False, write_concern=None):
  320. """Internal insert helper."""
  321. return_one = False
  322. if isinstance(docs, collections.MutableMapping):
  323. return_one = True
  324. docs = [docs]
  325. ids = []
  326. if manipulate:
  327. def gen():
  328. """Generator that applies SON manipulators to each document
  329. and adds _id if necessary.
  330. """
  331. _db = self.__database
  332. for doc in docs:
  333. # Apply user-configured SON manipulators. This order of
  334. # operations is required for backwards compatibility,
  335. # see PYTHON-709.
  336. doc = _db._apply_incoming_manipulators(doc, self)
  337. if '_id' not in doc:
  338. doc['_id'] = ObjectId()
  339. doc = _db._apply_incoming_copying_manipulators(doc, self)
  340. ids.append(doc['_id'])
  341. yield doc
  342. else:
  343. def gen():
  344. """Generator that only tracks existing _ids."""
  345. for doc in docs:
  346. ids.append(doc.get('_id'))
  347. yield doc
  348. concern = (write_concern or self.write_concern).document
  349. safe = concern.get("w") != 0
  350. if sock_info.max_wire_version > 1 and safe:
  351. # Insert command.
  352. command = SON([('insert', self.name),
  353. ('ordered', ordered)])
  354. if concern:
  355. command['writeConcern'] = concern
  356. results = message._do_batched_write_command(
  357. self.database.name + ".$cmd", _INSERT, command,
  358. gen(), check_keys, self.codec_options, sock_info)
  359. _check_write_command_response(results)
  360. else:
  361. # Legacy batched OP_INSERT.
  362. message._do_batched_insert(self.__full_name, gen(), check_keys,
  363. safe, concern, not ordered,
  364. self.codec_options, sock_info)
  365. if return_one:
  366. return ids[0]
  367. else:
  368. return ids
  369. def insert_one(self, document):
  370. """Insert a single document.
  371. >>> db.test.count({'x': 1})
  372. 0
  373. >>> result = db.test.insert_one({'x': 1})
  374. >>> result.inserted_id
  375. ObjectId('54f112defba522406c9cc208')
  376. >>> db.test.find_one({'x': 1})
  377. {u'x': 1, u'_id': ObjectId('54f112defba522406c9cc208')}
  378. :Parameters:
  379. - `document`: The document to insert. Must be a mutable mapping
  380. type. If the document does not have an _id field one will be
  381. added automatically.
  382. :Returns:
  383. - An instance of :class:`~pymongo.results.InsertOneResult`.
  384. .. versionadded:: 3.0
  385. """
  386. common.validate_is_mutable_mapping("document", document)
  387. if "_id" not in document:
  388. document["_id"] = ObjectId()
  389. with self._socket_for_writes() as sock_info:
  390. return InsertOneResult(self._insert(sock_info, document),
  391. self.write_concern.acknowledged)
  392. def insert_many(self, documents, ordered=True):
  393. """Insert a list of documents.
  394. >>> db.test.count()
  395. 0
  396. >>> result = db.test.insert_many([{'x': i} for i in range(2)])
  397. >>> result.inserted_ids
  398. [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')]
  399. >>> db.test.count()
  400. 2
  401. :Parameters:
  402. - `documents`: A list of documents to insert.
  403. - `ordered` (optional): If ``True`` (the default) documents will be
  404. inserted on the server serially, in the order provided. If an error
  405. occurs all remaining inserts are aborted. If ``False``, documents
  406. will be inserted on the server in arbitrary order, possibly in
  407. parallel, and all document inserts will be attempted.
  408. :Returns:
  409. An instance of :class:`~pymongo.results.InsertManyResult`.
  410. .. versionadded:: 3.0
  411. """
  412. if not isinstance(documents, list) or not documents:
  413. raise TypeError("documents must be a non-empty list")
  414. inserted_ids = []
  415. def gen():
  416. """A generator that validates documents and handles _ids."""
  417. for document in documents:
  418. common.validate_is_mutable_mapping("document", document)
  419. if "_id" not in document:
  420. document["_id"] = ObjectId()
  421. inserted_ids.append(document["_id"])
  422. yield (_INSERT, document)
  423. blk = _Bulk(self, ordered)
  424. blk.ops = [doc for doc in gen()]
  425. blk.execute(self.write_concern.document)
  426. return InsertManyResult(inserted_ids, self.write_concern.acknowledged)
  427. def _update(self, sock_info, filter, document, upsert=False,
  428. check_keys=True, multi=False, manipulate=False,
  429. write_concern=None):
  430. """Internal update / replace helper."""
  431. common.validate_is_mapping("filter", filter)
  432. common.validate_boolean("upsert", upsert)
  433. if manipulate:
  434. document = self.__database._fix_incoming(document, self)
  435. concern = (write_concern or self.write_concern).document
  436. safe = concern.get("w") != 0
  437. if sock_info.max_wire_version > 1 and safe:
  438. # Update command.
  439. command = SON([('update', self.name)])
  440. if concern:
  441. command['writeConcern'] = concern
  442. docs = [SON([('q', filter), ('u', document),
  443. ('multi', multi), ('upsert', upsert)])]
  444. results = message._do_batched_write_command(
  445. self.database.name + '.$cmd', _UPDATE, command,
  446. docs, check_keys, self.codec_options, sock_info)
  447. _check_write_command_response(results)
  448. _, result = results[0]
  449. # Add the updatedExisting field for compatibility.
  450. if result.get('n') and 'upserted' not in result:
  451. result['updatedExisting'] = True
  452. else:
  453. result['updatedExisting'] = False
  454. # MongoDB >= 2.6.0 returns the upsert _id in an array
  455. # element. Break it out for backward compatibility.
  456. if 'upserted' in result:
  457. result['upserted'] = result['upserted'][0]['_id']
  458. return result
  459. else:
  460. # Legacy OP_UPDATE.
  461. request_id, msg, max_size = message.update(
  462. self.__full_name, upsert, multi, filter, document, safe,
  463. concern, check_keys, self.codec_options)
  464. return sock_info.legacy_write(request_id, msg, max_size, safe)
  465. def replace_one(self, filter, replacement, upsert=False):
  466. """Replace a single document matching the filter.
  467. >>> for doc in db.test.find({}):
  468. ... print(doc)
  469. ...
  470. {u'x': 1, u'_id': ObjectId('54f4c5befba5220aa4d6dee7')}
  471. >>> result = db.test.replace_one({'x': 1}, {'y': 1})
  472. >>> result.matched_count
  473. 1
  474. >>> result.modified_count
  475. 1
  476. >>> for doc in db.test.find({}):
  477. ... print(doc)
  478. ...
  479. {u'y': 1, u'_id': ObjectId('54f4c5befba5220aa4d6dee7')}
  480. The *upsert* option can be used to insert a new document if a matching
  481. document does not exist.
  482. >>> result = db.test.replace_one({'x': 1}, {'x': 1}, True)
  483. >>> result.matched_count
  484. 0
  485. >>> result.modified_count
  486. 0
  487. >>> result.upserted_id
  488. ObjectId('54f11e5c8891e756a6e1abd4')
  489. >>> db.test.find_one({'x': 1})
  490. {u'x': 1, u'_id': ObjectId('54f11e5c8891e756a6e1abd4')}
  491. :Parameters:
  492. - `filter`: A query that matches the document to replace.
  493. - `replacement`: The new document.
  494. - `upsert` (optional): If ``True``, perform an insert if no documents
  495. match the filter.
  496. :Returns:
  497. - An instance of :class:`~pymongo.results.UpdateResult`.
  498. .. versionadded:: 3.0
  499. """
  500. common.validate_ok_for_replace(replacement)
  501. with self._socket_for_writes() as sock_info:
  502. result = self._update(sock_info, filter, replacement, upsert)
  503. return UpdateResult(result, self.write_concern.acknowledged)
  504. def update_one(self, filter, update, upsert=False):
  505. """Update a single document matching the filter.
  506. >>> for doc in db.test.find():
  507. ... print(doc)
  508. ...
  509. {u'x': 1, u'_id': 0}
  510. {u'x': 1, u'_id': 1}
  511. {u'x': 1, u'_id': 2}
  512. >>> result = db.test.update_one({'x': 1}, {'$inc': {'x': 3}})
  513. >>> result.matched_count
  514. 1
  515. >>> result.modified_count
  516. 1
  517. >>> for doc in db.test.find():
  518. ... print(doc)
  519. ...
  520. {u'x': 4, u'_id': 0}
  521. {u'x': 1, u'_id': 1}
  522. {u'x': 1, u'_id': 2}
  523. :Parameters:
  524. - `filter`: A query that matches the document to update.
  525. - `update`: The modifications to apply.
  526. - `upsert` (optional): If ``True``, perform an insert if no documents
  527. match the filter.
  528. :Returns:
  529. - An instance of :class:`~pymongo.results.UpdateResult`.
  530. .. versionadded:: 3.0
  531. """
  532. common.validate_ok_for_update(update)
  533. with self._socket_for_writes() as sock_info:
  534. result = self._update(sock_info, filter, update,
  535. upsert, check_keys=False)
  536. return UpdateResult(result, self.write_concern.acknowledged)
  537. def update_many(self, filter, update, upsert=False):
  538. """Update one or more documents that match the filter.
  539. >>> for doc in db.test.find():
  540. ... print(doc)
  541. ...
  542. {u'x': 1, u'_id': 0}
  543. {u'x': 1, u'_id': 1}
  544. {u'x': 1, u'_id': 2}
  545. >>> result = db.test.update_many({'x': 1}, {'$inc': {'x': 3}})
  546. >>> result.matched_count
  547. 3
  548. >>> result.modified_count
  549. 3
  550. >>> for doc in db.test.find():
  551. ... print(doc)
  552. ...
  553. {u'x': 4, u'_id': 0}
  554. {u'x': 4, u'_id': 1}
  555. {u'x': 4, u'_id': 2}
  556. :Parameters:
  557. - `filter`: A query that matches the documents to update.
  558. - `update`: The modifications to apply.
  559. - `upsert` (optional): If ``True``, perform an insert if no documents
  560. match the filter.
  561. :Returns:
  562. - An instance of :class:`~pymongo.results.UpdateResult`.
  563. .. versionadded:: 3.0
  564. """
  565. common.validate_ok_for_update(update)
  566. with self._socket_for_writes() as sock_info:
  567. result = self._update(sock_info, filter, update, upsert,
  568. check_keys=False, multi=True)
  569. return UpdateResult(result, self.write_concern.acknowledged)
  570. def drop(self):
  571. """Alias for :meth:`~pymongo.database.Database.drop_collection`.
  572. The following two calls are equivalent:
  573. >>> db.foo.drop()
  574. >>> db.drop_collection("foo")
  575. """
  576. self.__database.drop_collection(self.__name)
  577. def _delete(self, sock_info, filter, multi, write_concern=None):
  578. """Internal delete helper."""
  579. common.validate_is_mapping("filter", filter)
  580. concern = (write_concern or self.write_concern).document
  581. safe = concern.get("w") != 0
  582. if sock_info.max_wire_version > 1 and safe:
  583. # Delete command.
  584. command = SON([('delete', self.name)])
  585. if concern:
  586. command['writeConcern'] = concern
  587. docs = [SON([('q', filter), ('limit', int(not multi))])]
  588. results = message._do_batched_write_command(
  589. self.database.name + '.$cmd', _DELETE, command,
  590. docs, False, self.codec_options, sock_info)
  591. _check_write_command_response(results)
  592. _, result = results[0]
  593. return result
  594. else:
  595. # Legacy OP_DELETE.
  596. request_id, msg, max_size = message.delete(
  597. self.__full_name, filter, safe, concern,
  598. self.codec_options, int(not multi))
  599. return sock_info.legacy_write(request_id, msg, max_size, safe)
  600. def delete_one(self, filter):
  601. """Delete a single document matching the filter.
  602. >>> db.test.count({'x': 1})
  603. 3
  604. >>> result = db.test.delete_one({'x': 1})
  605. >>> result.deleted_count
  606. 1
  607. >>> db.test.count({'x': 1})
  608. 2
  609. :Parameters:
  610. - `filter`: A query that matches the document to delete.
  611. :Returns:
  612. - An instance of :class:`~pymongo.results.DeleteResult`.
  613. .. versionadded:: 3.0
  614. """
  615. with self._socket_for_writes() as sock_info:
  616. return DeleteResult(self._delete(sock_info, filter, False),
  617. self.write_concern.acknowledged)
  618. def delete_many(self, filter):
  619. """Delete one or more documents matching the filter.
  620. >>> db.test.count({'x': 1})
  621. 3
  622. >>> result = db.test.delete_many({'x': 1})
  623. >>> result.deleted_count
  624. 3
  625. >>> db.test.count({'x': 1})
  626. 0
  627. :Parameters:
  628. - `filter`: A query that matches the documents to delete.
  629. :Returns:
  630. - An instance of :class:`~pymongo.results.DeleteResult`.
  631. .. versionadded:: 3.0
  632. """
  633. with self._socket_for_writes() as sock_info:
  634. return DeleteResult(self._delete(sock_info, filter, True),
  635. self.write_concern.acknowledged)
  636. def find_one(self, filter=None, *args, **kwargs):
  637. """Get a single document from the database.
  638. All arguments to :meth:`find` are also valid arguments for
  639. :meth:`find_one`, although any `limit` argument will be
  640. ignored. Returns a single document, or ``None`` if no matching
  641. document is found.
  642. The :meth:`find_one` method obeys the :attr:`read_preference` of
  643. this :class:`Collection`.
  644. :Parameters:
  645. - `filter` (optional): a dictionary specifying
  646. the query to be performed OR any other type to be used as
  647. the value for a query for ``"_id"``.
  648. - `*args` (optional): any additional positional arguments
  649. are the same as the arguments to :meth:`find`.
  650. - `**kwargs` (optional): any additional keyword arguments
  651. are the same as the arguments to :meth:`find`.
  652. - `max_time_ms` (optional): a value for max_time_ms may be
  653. specified as part of `**kwargs`, e.g.
  654. >>> find_one(max_time_ms=100)
  655. """
  656. if (filter is not None and not
  657. isinstance(filter, collections.Mapping)):
  658. filter = {"_id": filter}
  659. max_time_ms = kwargs.pop("max_time_ms", None)
  660. cursor = self.find(filter,
  661. *args, **kwargs).max_time_ms(max_time_ms)
  662. for result in cursor.limit(-1):
  663. return result
  664. return None
  665. def find(self, *args, **kwargs):
  666. """Query the database.
  667. The `filter` argument is a prototype document that all results
  668. must match. For example:
  669. >>> db.test.find({"hello": "world"})
  670. only matches documents that have a key "hello" with value
  671. "world". Matches can have other keys *in addition* to
  672. "hello". The `projection` argument is used to specify a subset
  673. of fields that should be included in the result documents. By
  674. limiting results to a certain subset of fields you can cut
  675. down on network traffic and decoding time.
  676. Raises :class:`TypeError` if any of the arguments are of
  677. improper type. Returns an instance of
  678. :class:`~pymongo.cursor.Cursor` corresponding to this query.
  679. The :meth:`find` method obeys the :attr:`read_preference` of
  680. this :class:`Collection`.
  681. :Parameters:
  682. - `filter` (optional): a SON object specifying elements which
  683. must be present for a document to be included in the
  684. result set
  685. - `projection` (optional): a list of field names that should be
  686. returned in the result set or a dict specifying the fields
  687. to include or exclude. If `projection` is a list "_id" will
  688. always be returned. Use a dict to exclude fields from
  689. the result (e.g. projection={'_id': False}).
  690. - `skip` (optional): the number of documents to omit (from
  691. the start of the result set) when returning the results
  692. - `limit` (optional): the maximum number of results to
  693. return
  694. - `no_cursor_timeout` (optional): if False (the default), any
  695. returned cursor is closed by the server after 10 minutes of
  696. inactivity. If set to True, the returned cursor will never
  697. time out on the server. Care should be taken to ensure that
  698. cursors with no_cursor_timeout turned on are properly closed.
  699. - `cursor_type` (optional): the type of cursor to return. The valid
  700. options are defined by :class:`~pymongo.cursor.CursorType`:
  701. - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
  702. this find call will return a standard cursor over the result set.
  703. - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
  704. find call will be a tailable cursor - tailable cursors are only
  705. for use with capped collections. They are not closed when the
  706. last data is retrieved but are kept open and the cursor location
  707. marks the final document position. If more data is received
  708. iteration of the cursor will continue from the last document
  709. received. For details, see the `tailable cursor documentation
  710. <http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_.
  711. - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
  712. of this find call will be a tailable cursor with the await flag
  713. set. The server will wait for a few seconds after returning the
  714. full result set so that it can capture and return additional data
  715. added during the query.
  716. - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
  717. find call will be an exhaust cursor. MongoDB will stream batched
  718. results to the client without waiting for the client to request
  719. each batch, reducing latency. See notes on compatibility below.
  720. - `sort` (optional): a list of (key, direction) pairs
  721. specifying the sort order for this query. See
  722. :meth:`~pymongo.cursor.Cursor.sort` for details.
  723. - `allow_partial_results` (optional): if True, mongos will return
  724. partial results if some shards are down instead of returning an
  725. error.
  726. - `oplog_replay` (optional): If True, set the oplogReplay query
  727. flag.
  728. - `modifiers` (optional): A dict specifying the MongoDB `query
  729. modifiers`_ that should be used for this query. For example::
  730. >>> db.test.find(modifiers={"$maxTimeMS": 500})
  731. - `batch_size` (optional): Limits the number of documents returned in
  732. a single batch.
  733. - `manipulate` (optional): **DEPRECATED** - If True (the default),
  734. apply any outgoing SON manipulators before returning.
  735. .. note:: There are a number of caveats to using
  736. :attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type:
  737. - The `limit` option can not be used with an exhaust cursor.
  738. - Exhaust cursors are not supported by mongos and can not be
  739. used with a sharded cluster.
  740. - A :class:`~pymongo.cursor.Cursor` instance created with the
  741. :attr:`~pymongo.cursor.CursorType.EXHAUST` cursor_type requires an
  742. exclusive :class:`~socket.socket` connection to MongoDB. If the
  743. :class:`~pymongo.cursor.Cursor` is discarded without being
  744. completely iterated the underlying :class:`~socket.socket`
  745. connection will be closed and discarded without being returned to
  746. the connection pool.
  747. .. versionchanged:: 3.0
  748. Changed the parameter names `spec`, `fields`, `timeout`, and
  749. `partial` to `filter`, `projection`, `no_cursor_timeout`, and
  750. `allow_partial_results` respectively.
  751. Added the `cursor_type`, `oplog_replay`, and `modifiers` options.
  752. Removed the `network_timeout`, `read_preference`, `tag_sets`,
  753. `secondary_acceptable_latency_ms`, `max_scan`, `snapshot`,
  754. `tailable`, `await_data`, `exhaust`, `as_class`, and slave_okay
  755. parameters. Removed `compile_re` option: PyMongo now always
  756. represents BSON regular expressions as :class:`~bson.regex.Regex`
  757. objects. Use :meth:`~bson.regex.Regex.try_compile` to attempt to
  758. convert from a BSON regular expression to a Python regular
  759. expression object. Soft deprecated the `manipulate` option.
  760. .. versionchanged:: 2.7
  761. Added `compile_re` option. If set to False, PyMongo represented BSON
  762. regular expressions as :class:`~bson.regex.Regex` objects instead of
  763. attempting to compile BSON regular expressions as Python native
  764. regular expressions, thus preventing errors for some incompatible
  765. patterns, see `PYTHON-500`_.
  766. .. versionadded:: 2.3
  767. The `tag_sets` and `secondary_acceptable_latency_ms` parameters.
  768. .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
  769. .. _query modifiers:
  770. http://docs.mongodb.org/manual/reference/operator/query-modifier/
  771. .. mongodoc:: find
  772. """
  773. return Cursor(self, *args, **kwargs)
  774. def parallel_scan(self, num_cursors):
  775. """Scan this entire collection in parallel.
  776. Returns a list of up to ``num_cursors`` cursors that can be iterated
  777. concurrently. As long as the collection is not modified during
  778. scanning, each document appears once in one of the cursors result
  779. sets.
  780. For example, to process each document in a collection using some
  781. thread-safe ``process_document()`` function:
  782. >>> def process_cursor(cursor):
  783. ... for document in cursor:
  784. ... # Some thread-safe processing function:
  785. ... process_document(document)
  786. >>>
  787. >>> # Get up to 4 cursors.
  788. ...
  789. >>> cursors = collection.parallel_scan(4)
  790. >>> threads = [
  791. ... threading.Thread(target=process_cursor, args=(cursor,))
  792. ... for cursor in cursors]
  793. >>>
  794. >>> for thread in threads:
  795. ... thread.start()
  796. >>>
  797. >>> for thread in threads:
  798. ... thread.join()
  799. >>>
  800. >>> # All documents have now been processed.
  801. The :meth:`parallel_scan` method obeys the :attr:`read_preference` of
  802. this :class:`Collection`.
  803. :Parameters:
  804. - `num_cursors`: the number of cursors to return
  805. .. note:: Requires server version **>= 2.5.5**.
  806. .. versionchanged:: 3.0
  807. Removed support for arbitrary keyword arguments, since
  808. the parallelCollectionScan command has no optional arguments.
  809. """
  810. cmd = SON([('parallelCollectionScan', self.__name),
  811. ('numCursors', num_cursors)])
  812. with self._socket_for_reads() as (sock_info, slave_ok):
  813. result = self._command(sock_info, cmd, slave_ok)
  814. return [CommandCursor(self, cursor['cursor'], sock_info.address)
  815. for cursor in result['cursors']]
  816. def _count(self, cmd):
  817. """Internal count helper."""
  818. with self._socket_for_reads() as (sock_info, slave_ok):
  819. res = self._command(sock_info, cmd, slave_ok,
  820. allowable_errors=["ns missing"])
  821. if res.get("errmsg", "") == "ns missing":
  822. return 0
  823. return int(res["n"])
  824. def count(self, filter=None, **kwargs):
  825. """Get the number of documents in this collection.
  826. All optional count parameters should be passed as keyword arguments
  827. to this method. Valid options include:
  828. - `hint` (string or list of tuples): The index to use. Specify either
  829. the index name as a string or the index specification as a list of
  830. tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]).
  831. - `limit` (int): The maximum number of documents to count.
  832. - `skip` (int): The number of matching documents to skip before
  833. returning results.
  834. - `maxTimeMS` (int): The maximum amount of time to allow the count
  835. command to run, in milliseconds.
  836. The :meth:`count` method obeys the :attr:`read_preference` of
  837. this :class:`Collection`.
  838. :Parameters:
  839. - `filter` (optional): A query document that selects which documents
  840. to count in the collection.
  841. - `**kwargs` (optional): See list of options above.
  842. """
  843. cmd = SON([("count", self.__name)])
  844. if filter is not None:
  845. if "query" in kwargs:
  846. raise ConfigurationError("can't pass both filter and query")
  847. kwargs["query"] = filter
  848. if "hint" in kwargs and not isinstance(kwargs["hint"], string_type):
  849. kwargs["hint"] = helpers._index_document(kwargs["hint"])
  850. cmd.update(kwargs)
  851. return self._count(cmd)
  852. def create_indexes(self, indexes):
  853. """Create one or more indexes on this collection.
  854. >>> from pymongo import IndexModel, ASCENDING, DESCENDING
  855. >>> index1 = IndexModel([("hello", DESCENDING),
  856. ... ("world", ASCENDING)], name="hello_world")
  857. >>> index2 = IndexModel([("goodbye", DESCENDING)])
  858. >>> db.test.create_indexes([index1, index2])
  859. ["hello_world"]
  860. :Parameters:
  861. - `indexes`: A list of :class:`~pymongo.operations.IndexModel`
  862. instances.
  863. .. note:: `create_indexes` uses the ``createIndexes`` command
  864. introduced in MongoDB **2.6** and cannot be used with earlier
  865. versions.
  866. .. versionadded:: 3.0
  867. """
  868. if not isinstance(indexes, list):
  869. raise TypeError("indexes must be a list")
  870. names = []
  871. def gen_indexes():
  872. for index in indexes:
  873. if not isinstance(index, IndexModel):
  874. raise TypeError("%r is not an instance of "
  875. "pymongo.operations.IndexModel" % (index,))
  876. document = index.document
  877. names.append(document["name"])
  878. yield document
  879. cmd = SON([('createIndexes', self.name),
  880. ('indexes', list(gen_indexes()))])
  881. with self._socket_for_writes() as sock_info:
  882. self._command(
  883. sock_info, cmd, read_preference=ReadPreference.PRIMARY)
  884. return names
  885. def __create_index(self, keys, index_options):
  886. """Internal create index helper.
  887. :Parameters:
  888. - `keys`: a list of tuples [(key, type), (key, type), ...]
  889. - `index_options`: a dict of index options.
  890. """
  891. index_doc = helpers._index_document(keys)
  892. index = {"key": index_doc}
  893. index.update(index_options)
  894. with self._socket_for_writes() as sock_info:
  895. cmd = SON([('createIndexes', self.name), ('indexes', [index])])
  896. try:
  897. self._command(
  898. sock_info, cmd, read_preference=ReadPreference.PRIMARY)
  899. except OperationFailure as exc:
  900. if exc.code in common.COMMAND_NOT_FOUND_CODES:
  901. index["ns"] = self.__full_name
  902. wcn = (self.write_concern if
  903. self.write_concern.acknowledged else WriteConcern())
  904. self.__database.system.indexes._insert(
  905. sock_info, index, True, False, False, wcn)
  906. else:
  907. raise
  908. def create_index(self, keys, **kwargs):
  909. """Creates an index on this collection.
  910. Takes either a single key or a list of (key, direction) pairs.
  911. The key(s) must be an instance of :class:`basestring`
  912. (:class:`str` in python 3), and the direction(s) must be one of
  913. (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
  914. :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOHAYSTACK`,
  915. :data:`~pymongo.GEOSPHERE`, :data:`~pymongo.HASHED`,
  916. :data:`~pymongo.TEXT`).
  917. To create a single key ascending index on the key ``'mike'`` we just
  918. use a string argument::
  919. >>> my_collection.create_index("mike")
  920. For a compound index on ``'mike'`` descending and ``'eliot'``
  921. ascending we need to use a list of tuples::
  922. >>> my_collection.create_index([("mike", pymongo.DESCENDING),
  923. ... ("eliot", pymongo.ASCENDING)])
  924. All optional index creation parameters should be passed as
  925. keyword arguments to this method. For example::
  926. >>> my_collection.create_index([("mike", pymongo.DESCENDING)],
  927. ... background=True)
  928. Valid options include, but are not limited to:
  929. - `name`: custom name to use for this index - if none is
  930. given, a name will be generated.
  931. - `unique`: if ``True`` creates a uniqueness constraint on the index.
  932. - `background`: if ``True`` this index should be created in the
  933. background.
  934. - `sparse`: if ``True``, omit from the index any documents that lack
  935. the indexed field.
  936. - `bucketSize`: for use with geoHaystack indexes.
  937. Number of documents to group together within a certain proximity
  938. to a given longitude and latitude.
  939. - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
  940. index.
  941. - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
  942. index.
  943. - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
  944. collection. MongoDB will automatically delete documents from
  945. this collection after <int> seconds. The indexed field must
  946. be a UTC datetime or the data will not expire.
  947. See the MongoDB documentation for a full list of supported options by
  948. server version.
  949. .. warning:: `dropDups` is not supported by MongoDB 2.7.5 or newer. The
  950. option is silently ignored by the server and unique index builds
  951. using the option will fail if a duplicate value is detected.
  952. .. note:: `expireAfterSeconds` requires server version **>= 2.2**
  953. :Parameters:
  954. - `keys`: a single key or a list of (key, direction)
  955. pairs specifying the index to create
  956. - `**kwargs` (optional): any additional index creation
  957. options (see the above list) should be passed as keyword
  958. arguments
  959. .. versionchanged:: 3.0
  960. Renamed `key_or_list` to `keys`. Removed the `cache_for` option.
  961. :meth:`create_index` no longer caches index names. Removed support
  962. for the drop_dups and bucket_size aliases.
  963. .. mongodoc:: indexes
  964. """
  965. keys = helpers._index_list(keys)
  966. name = kwargs.setdefault("name", helpers._gen_index_name(keys))
  967. self.__create_index(keys, kwargs)
  968. return name
  969. def ensure_index(self, key_or_list, cache_for=300, **kwargs):
  970. """**DEPRECATED** - Ensures that an index exists on this collection.
  971. .. versionchanged:: 3.0
  972. **DEPRECATED**
  973. """
  974. warnings.warn("ensure_index is deprecated. Use create_index instead.",
  975. DeprecationWarning, stacklevel=2)
  976. # The types supported by datetime.timedelta.
  977. if not (isinstance(cache_for, integer_types) or
  978. isinstance(cache_for, float)):
  979. raise TypeError("cache_for must be an integer or float.")
  980. if "drop_dups" in kwargs:
  981. kwargs["dropDups"] = kwargs.pop("drop_dups")
  982. if "bucket_size" in kwargs:
  983. kwargs["bucketSize"] = kwargs.pop("bucket_size")
  984. keys = helpers._index_list(key_or_list)
  985. name = kwargs.setdefault("name", helpers._gen_index_name(keys))
  986. if not self.__database.client._cached(self.__database.name,
  987. self.__name, name):
  988. self.__create_index(keys, kwargs)
  989. self.__database.client._cache_index(self.__database.name,
  990. self.__name, name, cache_for)
  991. return name
  992. return None
  993. def drop_indexes(self):
  994. """Drops all indexes on this collection.
  995. Can be used on non-existant collections or collections with no indexes.
  996. Raises OperationFailure on an error.
  997. """
  998. self.__database.client._purge_index(self.__database.name, self.__name)
  999. self.drop_index("*")
  1000. def drop_index(self, index_or_name):
  1001. """Drops the specified index on this collection.
  1002. Can be used on non-existant collections or collections with no
  1003. indexes. Raises OperationFailure on an error (e.g. trying to
  1004. drop an index that does not exist). `index_or_name`
  1005. can be either an index name (as returned by `create_index`),
  1006. or an index specifier (as passed to `create_index`). An index
  1007. specifier should be a list of (key, direction) pairs. Raises
  1008. TypeError if index is not an instance of (str, unicode, list).
  1009. .. warning::
  1010. if a custom name was used on index creation (by
  1011. passing the `name` parameter to :meth:`create_index` or
  1012. :meth:`ensure_index`) the index **must** be dropped by name.
  1013. :Parameters:
  1014. - `index_or_name`: index (or name of index) to drop
  1015. """
  1016. name = index_or_name
  1017. if isinstance(index_or_name, list):
  1018. name = helpers._gen_index_name(index_or_name)
  1019. if not isinstance(name, string_type):
  1020. raise TypeError("index_or_name must be an index name or list")
  1021. self.__database.client._purge_index(
  1022. self.__database.name, self.__name, name)
  1023. cmd = SON([("dropIndexes", self.__name), ("index", name)])
  1024. with self._socket_for_writes() as sock_info:
  1025. self._command(sock_info,
  1026. cmd,
  1027. read_preference=ReadPreference.PRIMARY,
  1028. allowable_errors=["ns not found"])
  1029. def reindex(self):
  1030. """Rebuilds all indexes on this collection.
  1031. .. warning:: reindex blocks all other operations (indexes
  1032. are built in the foreground) and will be slow for large
  1033. collections.
  1034. """
  1035. cmd = SON([("reIndex", self.__name)])
  1036. with self._socket_for_writes() as sock_info:
  1037. return self._command(
  1038. sock_info, cmd, read_preference=ReadPreference.PRIMARY)
  1039. def list_indexes(self):
  1040. """Get a cursor over the index documents for this collection.
  1041. >>> for index in db.test.list_indexes():
  1042. ... print(index)
  1043. ...
  1044. SON([(u'v', 1), (u'key', SON([(u'_id', 1)])),
  1045. (u'name', u'_id_'), (u'ns', u'test.test')])
  1046. :Returns:
  1047. An instance of :class:`~pymongo.command_cursor.CommandCursor`.
  1048. .. versionadded:: 3.0
  1049. """
  1050. codec_options = CodecOptions(SON)
  1051. coll = self.with_options(codec_options)
  1052. with self._socket_for_primary_reads() as (sock_info, slave_ok):
  1053. if sock_info.max_wire_version > 2:
  1054. cmd = SON([("listIndexes", self.__name), ("cursor", {})])
  1055. cursor = self._command(sock_info, cmd, slave_ok,
  1056. ReadPreference.PRIMARY,
  1057. codec_options)["cursor"]
  1058. return CommandCursor(coll, cursor, sock_info.address)
  1059. else:
  1060. namespace = _UJOIN % (self.__database.name, "system.indexes")
  1061. res = helpers._first_batch(
  1062. sock_info, namespace, {"ns": self.__full_name},
  1063. 0, slave_ok, codec_options, ReadPreference.PRIMARY)
  1064. data = res["data"]
  1065. cursor = {
  1066. "id": res["cursor_id"],
  1067. "firstBatch": data,
  1068. "ns": namespace,
  1069. }
  1070. # Note that a collection can only have 64 indexes, so we don't
  1071. # technically have to pass len(data) here. There will never be
  1072. # an OP_GET_MORE call.
  1073. return CommandCursor(
  1074. coll, cursor, sock_info.address, len(data))
  1075. def index_information(self):
  1076. """Get information on this collection's indexes.
  1077. Returns a dictionary where the keys are index names (as
  1078. returned by create_index()) and the values are dictionaries
  1079. containing information about each index. The dictionary is
  1080. guaranteed to contain at least a single key, ``"key"`` which
  1081. is a list of (key, direction) pairs specifying the index (as
  1082. passed to create_index()). It will also contain any other
  1083. metadata about the indexes, except for the ``"ns"`` and
  1084. ``"name"`` keys, which are cleaned. Example output might look
  1085. like this:
  1086. >>> db.test.ensure_index("x", unique=True)
  1087. u'x_1'
  1088. >>> db.test.index_information()
  1089. {u'_id_': {u'key': [(u'_id', 1)]},
  1090. u'x_1': {u'unique': True, u'key': [(u'x', 1)]}}
  1091. """
  1092. cursor = self.list_indexes()
  1093. info = {}
  1094. for index in cursor:
  1095. index["key"] = index["key"].items()
  1096. index = dict(index)
  1097. info[index.pop("name")] = index
  1098. return info
  1099. def options(self):
  1100. """Get the options set on this collection.
  1101. Returns a dictionary of options and their values - see
  1102. :meth:`~pymongo.database.Database.create_collection` for more
  1103. information on the possible options. Returns an empty
  1104. dictionary if the collection has not been created yet.
  1105. """
  1106. with self._socket_for_primary_reads() as (sock_info, slave_ok):
  1107. if sock_info.max_wire_version > 2:
  1108. criteria = {"name": self.__name}
  1109. else:
  1110. criteria = {"name": self.__full_name}
  1111. cursor = self.__database._list_collections(sock_info,
  1112. slave_ok,
  1113. criteria)
  1114. result = None
  1115. for doc in cursor:
  1116. result = doc
  1117. break
  1118. if not result:
  1119. return {}
  1120. options = result.get("options", {})
  1121. if "create" in options:
  1122. del options["create"]
  1123. return options
  1124. def aggregate(self, pipeline, **kwargs):
  1125. """Perform an aggregation using the aggregation framework on this
  1126. collection.
  1127. All optional aggregate parameters should be passed as keyword arguments
  1128. to this method. Valid options include, but are not limited to:
  1129. - `allowDiskUse` (bool): Enables writing to temporary files. When set
  1130. to True, aggregation stages can write data to the _tmp subdirectory
  1131. of the --dbpath directory. The default is False.
  1132. - `maxTimeMS` (int): The maximum amount of time to allow the operation
  1133. to run in milliseconds.
  1134. - `batchSize` (int): The maximum number of documents to return per
  1135. batch. Ignored if the connected mongod or mongos does not support
  1136. returning aggregate results using a cursor, or `useCursor` is
  1137. ``False``.
  1138. - `useCursor` (bool): Requests that the `server` provide results
  1139. using a cursor, if possible. Ignored if the connected mongod or
  1140. mongos does not support returning aggregate results using a cursor.
  1141. The default is ``True``. Set this to ``False`` when upgrading a 2.4
  1142. or older sharded cluster to 2.6 or newer (see the warning below).
  1143. The :meth:`aggregate` method obeys the :attr:`read_preference` of this
  1144. :class:`Collection`. Please note that using the ``$out`` pipeline stage
  1145. requires a read preference of
  1146. :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY` (the default).
  1147. The server will raise an error if the ``$out`` pipeline stage is used
  1148. with any other read preference.
  1149. .. warning:: When upgrading a 2.4 or older sharded cluster to 2.6 or
  1150. newer the `useCursor` option **must** be set to ``False``
  1151. until all shards have been upgraded to 2.6 or newer.
  1152. .. note:: This method does not support the 'explain' option. Please
  1153. use :meth:`~pymongo.database.Database.command` instead. An
  1154. example is included in the :ref:`aggregate-examples` documentation.
  1155. :Parameters:
  1156. - `pipeline`: a list of aggregation pipeline stages
  1157. - `**kwargs` (optional): See list of options above.
  1158. :Returns:
  1159. A :class:`~pymongo.command_cursor.CommandCursor` over the result
  1160. set.
  1161. .. versionchanged:: 3.0
  1162. The :meth:`aggregate` method always returns a CommandCursor. The
  1163. pipeline argument must be a list.
  1164. .. versionchanged:: 2.7
  1165. When the cursor option is used, return
  1166. :class:`~pymongo.command_cursor.CommandCursor` instead of
  1167. :class:`~pymongo.cursor.Cursor`.
  1168. .. versionchanged:: 2.6
  1169. Added cursor support.
  1170. .. versionadded:: 2.3
  1171. .. seealso:: :doc:`/examples/aggregation`
  1172. .. _aggregate command:
  1173. http://docs.mongodb.org/manual/applications/aggregation
  1174. """
  1175. if not isinstance(pipeline, list):
  1176. raise TypeError("pipeline must be a list")
  1177. if "explain" in kwargs:
  1178. raise ConfigurationError("The explain option is not supported. "
  1179. "Use Database.command instead.")
  1180. cmd = SON([("aggregate", self.__name),
  1181. ("pipeline", pipeline)])
  1182. # Remove things that are not command options.
  1183. batch_size = common.validate_positive_integer_or_none(
  1184. "batchSize", kwargs.pop("batchSize", None))
  1185. use_cursor = common.validate_boolean(
  1186. "useCursor", kwargs.pop("useCursor", True))
  1187. # If the server does not support the "cursor" option we
  1188. # ignore useCursor and batchSize.
  1189. with self._socket_for_reads() as (sock_info, slave_ok):
  1190. if sock_info.max_wire_version > 0:
  1191. if use_cursor:
  1192. if "cursor" not in kwargs:
  1193. kwargs["cursor"] = {}
  1194. if batch_size is not None:
  1195. kwargs["cursor"]["batchSize"] = batch_size
  1196. cmd.update(kwargs)
  1197. result = self._command(sock_info, cmd, slave_ok)
  1198. if "cursor" in result:
  1199. cursor = result["cursor"]
  1200. else:
  1201. # Pre-MongoDB 2.6. Fake a cursor.
  1202. cursor = {
  1203. "id": 0,
  1204. "firstBatch": result["result"],
  1205. "ns": self.full_name,
  1206. }
  1207. return CommandCursor(
  1208. self, cursor, sock_info.address).batch_size(batch_size or 0)
  1209. # key and condition ought to be optional, but deprecation
  1210. # would be painful as argument order would have to change.
  1211. def group(self, key, condition, initial, reduce, finalize=None, **kwargs):
  1212. """Perform a query similar to an SQL *group by* operation.
  1213. Returns an array of grouped items.
  1214. The `key` parameter can be:
  1215. - ``None`` to use the entire document as a key.
  1216. - A :class:`list` of keys (each a :class:`basestring`
  1217. (:class:`str` in python 3)) to group by.
  1218. - A :class:`basestring` (:class:`str` in python 3), or
  1219. :class:`~bson.code.Code` instance containing a JavaScript
  1220. function to be applied to each document, returning the key
  1221. to group by.
  1222. The :meth:`group` method obeys the :attr:`read_preference` of this
  1223. :class:`Collection`.
  1224. :Parameters:
  1225. - `key`: fields to group by (see above description)
  1226. - `condition`: specification of rows to be
  1227. considered (as a :meth:`find` query specification)
  1228. - `initial`: initial value of the aggregation counter object
  1229. - `reduce`: aggregation function as a JavaScript string
  1230. - `finalize`: function to be called on each object in output list.
  1231. - `**kwargs` (optional): additional arguments to the group command
  1232. may be passed as keyword arguments to this helper method
  1233. .. versionchanged:: 2.2
  1234. Removed deprecated argument: command
  1235. """
  1236. group = {}
  1237. if isinstance(key, string_type):
  1238. group["$keyf"] = Code(key)
  1239. elif key is not None:
  1240. group = {"key": helpers._fields_list_to_dict(key, "key")}
  1241. group["ns"] = self.__name
  1242. group["$reduce"] = Code(reduce)
  1243. group["cond"] = condition
  1244. group["initial"] = initial
  1245. if finalize is not None:
  1246. group["finalize"] = Code(finalize)
  1247. cmd = SON([("group", group)])
  1248. cmd.update(kwargs)
  1249. with self._socket_for_reads() as (sock_info, slave_ok):
  1250. return self._command(sock_info, cmd, slave_ok)["retval"]
  1251. def rename(self, new_name, **kwargs):
  1252. """Rename this collection.
  1253. If operating in auth mode, client must be authorized as an
  1254. admin to perform this operation. Raises :class:`TypeError` if
  1255. `new_name` is not an instance of :class:`basestring`
  1256. (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName`
  1257. if `new_name` is not a valid collection name.
  1258. :Parameters:
  1259. - `new_name`: new name for this collection
  1260. - `**kwargs` (optional): additional arguments to the rename command
  1261. may be passed as keyword arguments to this helper method
  1262. (i.e. ``dropTarget=True``)
  1263. """
  1264. if not isinstance(new_name, string_type):
  1265. raise TypeError("new_name must be an "
  1266. "instance of %s" % (string_type.__name__,))
  1267. if not new_name or ".." in new_name:
  1268. raise InvalidName("collection names cannot be empty")
  1269. if new_name[0] == "." or new_name[-1] == ".":
  1270. raise InvalidName("collecion names must not start or end with '.'")
  1271. if "$" in new_name and not new_name.startswith("oplog.$main"):
  1272. raise InvalidName("collection names must not contain '$'")
  1273. new_name = "%s.%s" % (self.__database.name, new_name)
  1274. cmd = SON([("renameCollection", self.__full_name), ("to", new_name)])
  1275. cmd.update(kwargs)
  1276. with self._socket_for_writes() as sock_info:
  1277. sock_info.command('admin', cmd)
  1278. def distinct(self, key, filter=None, **kwargs):
  1279. """Get a list of distinct values for `key` among all documents
  1280. in this collection.
  1281. Raises :class:`TypeError` if `key` is not an instance of
  1282. :class:`basestring` (:class:`str` in python 3).
  1283. All optional distinct parameters should be passed as keyword arguments
  1284. to this method. Valid options include:
  1285. - `maxTimeMS` (int): The maximum amount of time to allow the count
  1286. command to run, in milliseconds.
  1287. The :meth:`distinct` method obeys the :attr:`read_preference` of
  1288. this :class:`Collection`.
  1289. :Parameters:
  1290. - `key`: name of the field for which we want to get the distinct
  1291. values
  1292. - `filter` (optional): A query document that specifies the documents
  1293. from which to retrieve the distinct values.
  1294. - `**kwargs` (optional): See list of options above.
  1295. """
  1296. if not isinstance(key, string_type):
  1297. raise TypeError("key must be an "
  1298. "instance of %s" % (string_type.__name__,))
  1299. cmd = SON([("distinct", self.__name),
  1300. ("key", key)])
  1301. if filter is not None:
  1302. if "query" in kwargs:
  1303. raise ConfigurationError("can't pass both filter and query")
  1304. kwargs["query"] = filter
  1305. cmd.update(kwargs)
  1306. with self._socket_for_reads() as (sock_info, slave_ok):
  1307. return self._command(sock_info, cmd, slave_ok)["values"]
  1308. def map_reduce(self, map, reduce, out, full_response=False, **kwargs):
  1309. """Perform a map/reduce operation on this collection.
  1310. If `full_response` is ``False`` (default) returns a
  1311. :class:`~pymongo.collection.Collection` instance containing
  1312. the results of the operation. Otherwise, returns the full
  1313. response from the server to the `map reduce command`_.
  1314. :Parameters:
  1315. - `map`: map function (as a JavaScript string)
  1316. - `reduce`: reduce function (as a JavaScript string)
  1317. - `out`: output collection name or `out object` (dict). See
  1318. the `map reduce command`_ documentation for available options.
  1319. Note: `out` options are order sensitive. :class:`~bson.son.SON`
  1320. can be used to specify multiple options.
  1321. e.g. SON([('replace', <collection name>), ('db', <database name>)])
  1322. - `full_response` (optional): if ``True``, return full response to
  1323. this command - otherwise just return the result collection
  1324. - `**kwargs` (optional): additional arguments to the
  1325. `map reduce command`_ may be passed as keyword arguments to this
  1326. helper method, e.g.::
  1327. >>> db.test.map_reduce(map, reduce, "myresults", limit=2)
  1328. .. note:: The :meth:`map_reduce` method does **not** obey the
  1329. :attr:`read_preference` of this :class:`Collection`. To run
  1330. mapReduce on a secondary use the :meth:`inline_map_reduce` method
  1331. instead.
  1332. .. seealso:: :doc:`/examples/aggregation`
  1333. .. versionchanged:: 2.2
  1334. Removed deprecated arguments: merge_output and reduce_output
  1335. .. _map reduce command: http://www.mongodb.org/display/DOCS/MapReduce
  1336. .. mongodoc:: mapreduce
  1337. """
  1338. if not isinstance(out, (string_type, collections.Mapping)):
  1339. raise TypeError("'out' must be an instance of "
  1340. "%s or a mapping" % (string_type.__name__,))
  1341. cmd = SON([("mapreduce", self.__name),
  1342. ("map", map),
  1343. ("reduce", reduce),
  1344. ("out", out)])
  1345. cmd.update(kwargs)
  1346. with self._socket_for_primary_reads() as (sock_info, slave_ok):
  1347. response = self._command(
  1348. sock_info, cmd, slave_ok, ReadPreference.PRIMARY)
  1349. if full_response or not response.get('result'):
  1350. return response
  1351. elif isinstance(response['result'], dict):
  1352. dbase = response['result']['db']
  1353. coll = response['result']['collection']
  1354. return self.__database.client[dbase][coll]
  1355. else:
  1356. return self.__database[response["result"]]
  1357. def inline_map_reduce(self, map, reduce, full_response=False, **kwargs):
  1358. """Perform an inline map/reduce operation on this collection.
  1359. Perform the map/reduce operation on the server in RAM. A result
  1360. collection is not created. The result set is returned as a list
  1361. of documents.
  1362. If `full_response` is ``False`` (default) returns the
  1363. result documents in a list. Otherwise, returns the full
  1364. response from the server to the `map reduce command`_.
  1365. The :meth:`inline_map_reduce` method obeys the :attr:`read_preference`
  1366. of this :class:`Collection`.
  1367. :Parameters:
  1368. - `map`: map function (as a JavaScript string)
  1369. - `reduce`: reduce function (as a JavaScript string)
  1370. - `full_response` (optional): if ``True``, return full response to
  1371. this command - otherwise just return the result collection
  1372. - `**kwargs` (optional): additional arguments to the
  1373. `map reduce command`_ may be passed as keyword arguments to this
  1374. helper method, e.g.::
  1375. >>> db.test.inline_map_reduce(map, reduce, limit=2)
  1376. """
  1377. cmd = SON([("mapreduce", self.__name),
  1378. ("map", map),
  1379. ("reduce", reduce),
  1380. ("out", {"inline": 1})])
  1381. cmd.update(kwargs)
  1382. with self._socket_for_reads() as (sock_info, slave_ok):
  1383. res = self._command(sock_info, cmd, slave_ok)
  1384. if full_response:
  1385. return res
  1386. else:
  1387. return res.get("results")
  1388. def __find_and_modify(self, filter, projection, sort, upsert=None,
  1389. return_document=ReturnDocument.BEFORE, **kwargs):
  1390. """Internal findAndModify helper."""
  1391. common.validate_is_mapping("filter", filter)
  1392. if not isinstance(return_document, bool):
  1393. raise ValueError("return_document must be "
  1394. "ReturnDocument.BEFORE or ReturnDocument.AFTER")
  1395. cmd = SON([("findAndModify", self.__name),
  1396. ("query", filter),
  1397. ("new", return_document)])
  1398. cmd.update(kwargs)
  1399. if projection is not None:
  1400. cmd["fields"] = helpers._fields_list_to_dict(projection,
  1401. "projection")
  1402. if sort is not None:
  1403. cmd["sort"] = helpers._index_document(sort)
  1404. if upsert is not None:
  1405. common.validate_boolean("upsert", upsert)
  1406. cmd["upsert"] = upsert
  1407. with self._socket_for_writes() as sock_info:
  1408. out = self._command(sock_info, cmd,
  1409. read_preference=ReadPreference.PRIMARY,
  1410. allowable_errors=[_NO_OBJ_ERROR])
  1411. return out.get("value")
  1412. def find_one_and_delete(self, filter,
  1413. projection=None, sort=None, **kwargs):
  1414. """Finds a single document and deletes it, returning the document.
  1415. >>> db.test.count({'x': 1})
  1416. 2
  1417. >>> db.test.find_one_and_delete({'x': 1})
  1418. {u'x': 1, u'_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
  1419. >>> db.test.count({'x': 1})
  1420. 1
  1421. If multiple documents match *filter*, a *sort* can be applied.
  1422. >>> for doc in db.test.find({'x': 1}):
  1423. ... print(doc)
  1424. ...
  1425. {u'x': 1, u'_id': 0}
  1426. {u'x': 1, u'_id': 1}
  1427. {u'x': 1, u'_id': 2}
  1428. >>> db.test.find_one_and_delete(
  1429. ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)])
  1430. {u'x': 1, u'_id': 2}
  1431. The *projection* option can be used to limit the fields returned.
  1432. >>> db.test.find_one_and_delete({'x': 1}, projection={'_id': False})
  1433. {u'x': 1}
  1434. :Parameters:
  1435. - `filter`: A query that matches the document to delete.
  1436. - `projection` (optional): a list of field names that should be
  1437. returned in the result document or a mapping specifying the fields
  1438. to include or exclude. If `projection` is a list "_id" will
  1439. always be returned. Use a mapping to exclude fields from
  1440. the result (e.g. projection={'_id': False}).
  1441. - `sort` (optional): a list of (key, direction) pairs
  1442. specifying the sort order for the query. If multiple documents
  1443. match the query, they are sorted and the first is deleted.
  1444. - `**kwargs` (optional): additional command arguments can be passed
  1445. as keyword arguments (for example maxTimeMS can be used with
  1446. recent server versions).
  1447. .. versionadded:: 3.0
  1448. """
  1449. kwargs['remove'] = True
  1450. return self.__find_and_modify(filter, projection, sort, **kwargs)
  1451. def find_one_and_replace(self, filter, replacement,
  1452. projection=None, sort=None, upsert=False,
  1453. return_document=ReturnDocument.BEFORE, **kwargs):
  1454. """Finds a single document and replaces it, returning either the
  1455. original or the replaced document.
  1456. The :meth:`find_one_and_replace` method differs from
  1457. :meth:`find_one_and_update` by replacing the document matched by
  1458. *filter*, rather than modifying the existing document.
  1459. >>> for doc in db.test.find({}):
  1460. ... print(doc)
  1461. ...
  1462. {u'x': 1, u'_id': 0}
  1463. {u'x': 1, u'_id': 1}
  1464. {u'x': 1, u'_id': 2}
  1465. >>> db.test.find_one_and_replace({'x': 1}, {'y': 1})
  1466. {u'x': 1, u'_id': 0}
  1467. >>> for doc in db.test.find({}):
  1468. ... print(doc)
  1469. ...
  1470. {u'y': 1, u'_id': 0}
  1471. {u'x': 1, u'_id': 1}
  1472. {u'x': 1, u'_id': 2}
  1473. :Parameters:
  1474. - `filter`: A query that matches the document to replace.
  1475. - `replacement`: The replacement document.
  1476. - `projection` (optional): A list of field names that should be
  1477. returned in the result document or a mapping specifying the fields
  1478. to include or exclude. If `projection` is a list "_id" will
  1479. always be returned. Use a mapping to exclude fields from
  1480. the result (e.g. projection={'_id': False}).
  1481. - `sort` (optional): a list of (key, direction) pairs
  1482. specifying the sort order for the query. If multiple documents
  1483. match the query, they are sorted and the first is replaced.
  1484. - `upsert` (optional): When ``True``, inserts a new document if no
  1485. document matches the query. Defaults to ``False``.
  1486. - `return_document`: If
  1487. :attr:`ReturnDocument.BEFORE` (the default),
  1488. returns the original document before it was replaced, or ``None``
  1489. if no document matches. If
  1490. :attr:`ReturnDocument.AFTER`, returns the replaced
  1491. or inserted document.
  1492. - `**kwargs` (optional): additional command arguments can be passed
  1493. as keyword arguments (for example maxTimeMS can be used with
  1494. recent server versions).
  1495. .. versionadded:: 3.0
  1496. """
  1497. common.validate_ok_for_replace(replacement)
  1498. kwargs['update'] = replacement
  1499. return self.__find_and_modify(filter, projection,
  1500. sort, upsert, return_document, **kwargs)
  1501. def find_one_and_update(self, filter, update,
  1502. projection=None, sort=None, upsert=False,
  1503. return_document=ReturnDocument.BEFORE, **kwargs):
  1504. """Finds a single document and updates it, returning either the
  1505. original or the updated document.
  1506. >>> db.test.find_one_and_update(
  1507. ... {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}})
  1508. {u'_id': 665, u'done': False, u'count': 25}}
  1509. By default :meth:`find_one_and_update` returns the original version of
  1510. the document before the update was applied. To return the updated
  1511. version of the document instead, use the *return_document* option.
  1512. >>> from pymongo import ReturnDocument
  1513. >>> db.example.find_one_and_update(
  1514. ... {'_id': 'userid'},
  1515. ... {'$inc': {'seq': 1}},
  1516. ... return_document=ReturnDocument.AFTER)
  1517. {u'_id': u'userid', u'seq': 1}
  1518. You can limit the fields returned with the *projection* option.
  1519. >>> db.example.find_one_and_update(
  1520. ... {'_id': 'userid'},
  1521. ... {'$inc': {'seq': 1}},
  1522. ... projection={'seq': True, '_id': False},
  1523. ... return_document=ReturnDocument.AFTER)
  1524. {u'seq': 2}
  1525. The *upsert* option can be used to create the document if it doesn't
  1526. already exist.
  1527. >>> db.example.delete_many({}).deleted_count
  1528. 1
  1529. >>> db.example.find_one_and_update(
  1530. ... {'_id': 'userid'},
  1531. ... {'$inc': {'seq': 1}},
  1532. ... projection={'seq': True, '_id': False},
  1533. ... upsert=True,
  1534. ... return_document=ReturnDocument.AFTER)
  1535. {u'seq': 1}
  1536. If multiple documents match *filter*, a *sort* can be applied.
  1537. >>> for doc in db.test.find({'done': True}):
  1538. ... print(doc)
  1539. ...
  1540. {u'_id': 665, u'done': True, u'result': {u'count': 26}}
  1541. {u'_id': 701, u'done': True, u'result': {u'count': 17}}
  1542. >>> db.test.find_one_and_update(
  1543. ... {'done': True},
  1544. ... {'$set': {'final': True}},
  1545. ... sort=[('_id', pymongo.DESCENDING)])
  1546. {u'_id': 701, u'done': True, u'result': {u'count': 17}}
  1547. :Parameters:
  1548. - `filter`: A query that matches the document to update.
  1549. - `update`: The update operations to apply.
  1550. - `projection` (optional): A list of field names that should be
  1551. returned in the result document or a mapping specifying the fields
  1552. to include or exclude. If `projection` is a list "_id" will
  1553. always be returned. Use a dict to exclude fields from
  1554. the result (e.g. projection={'_id': False}).
  1555. - `sort` (optional): a list of (key, direction) pairs
  1556. specifying the sort order for the query. If multiple documents
  1557. match the query, they are sorted and the first is updated.
  1558. - `upsert` (optional): When ``True``, inserts a new document if no
  1559. document matches the query. Defaults to ``False``.
  1560. - `return_document`: If
  1561. :attr:`ReturnDocument.BEFORE` (the default),
  1562. returns the original document before it was updated, or ``None``
  1563. if no document matches. If
  1564. :attr:`ReturnDocument.AFTER`, returns the updated
  1565. or inserted document.
  1566. - `**kwargs` (optional): additional command arguments can be passed
  1567. as keyword arguments (for example maxTimeMS can be used with
  1568. recent server versions).
  1569. .. versionadded:: 3.0
  1570. """
  1571. common.validate_ok_for_update(update)
  1572. kwargs['update'] = update
  1573. return self.__find_and_modify(filter, projection,
  1574. sort, upsert, return_document, **kwargs)
  1575. def save(self, to_save, manipulate=True, check_keys=True, **kwargs):
  1576. """Save a document in this collection.
  1577. **DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.
  1578. .. versionchanged:: 3.0
  1579. Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
  1580. operations.
  1581. """
  1582. warnings.warn("save is deprecated. Use insert_one or replace_one "
  1583. "instead", DeprecationWarning, stacklevel=2)
  1584. common.validate_is_mutable_mapping("to_save", to_save)
  1585. write_concern = None
  1586. if kwargs:
  1587. write_concern = WriteConcern(**kwargs)
  1588. with self._socket_for_writes() as sock_info:
  1589. if "_id" not in to_save:
  1590. return self._insert(sock_info, to_save, True,
  1591. check_keys, manipulate, write_concern)
  1592. else:
  1593. self._update(sock_info, {"_id": to_save["_id"]}, to_save, True,
  1594. check_keys, False, manipulate, write_concern)
  1595. return to_save.get("_id")
  1596. def insert(self, doc_or_docs, manipulate=True,
  1597. check_keys=True, continue_on_error=False, **kwargs):
  1598. """Insert a document(s) into this collection.
  1599. **DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead.
  1600. .. versionchanged:: 3.0
  1601. Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
  1602. operations.
  1603. """
  1604. warnings.warn("insert is deprecated. Use insert_one or insert_many "
  1605. "instead.", DeprecationWarning, stacklevel=2)
  1606. write_concern = None
  1607. if kwargs:
  1608. write_concern = WriteConcern(**kwargs)
  1609. with self._socket_for_writes() as sock_info:
  1610. return self._insert(sock_info, doc_or_docs, not continue_on_error,
  1611. check_keys, manipulate, write_concern)
  1612. def update(self, spec, document, upsert=False, manipulate=False,
  1613. multi=False, check_keys=True, **kwargs):
  1614. """Update a document(s) in this collection.
  1615. **DEPRECATED** - Use :meth:`replace_one`, :meth:`update_one`, or
  1616. :meth:`update_many` instead.
  1617. .. versionchanged:: 3.0
  1618. Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
  1619. operations.
  1620. """
  1621. warnings.warn("update is deprecated. Use replace_one, update_one or "
  1622. "update_many instead.", DeprecationWarning, stacklevel=2)
  1623. common.validate_is_mapping("spec", spec)
  1624. common.validate_is_mapping("document", document)
  1625. if document:
  1626. # If a top level key begins with '$' this is a modify operation
  1627. # and we should skip key validation. It doesn't matter which key
  1628. # we check here. Passing a document with a mix of top level keys
  1629. # starting with and without a '$' is invalid and the server will
  1630. # raise an appropriate exception.
  1631. first = next(iter(document))
  1632. if first.startswith('$'):
  1633. check_keys = False
  1634. write_concern = None
  1635. if kwargs:
  1636. write_concern = WriteConcern(**kwargs)
  1637. with self._socket_for_writes() as sock_info:
  1638. return self._update(sock_info, spec, document, upsert,
  1639. check_keys, multi, manipulate, write_concern)
  1640. def remove(self, spec_or_id=None, multi=True, **kwargs):
  1641. """Remove a document(s) from this collection.
  1642. **DEPRECATED** - Use :meth:`delete_one` or :meth:`delete_many` instead.
  1643. .. versionchanged:: 3.0
  1644. Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
  1645. operations.
  1646. """
  1647. warnings.warn("remove is deprecated. Use delete_one or delete_many "
  1648. "instead.", DeprecationWarning, stacklevel=2)
  1649. if spec_or_id is None:
  1650. spec_or_id = {}
  1651. if not isinstance(spec_or_id, collections.Mapping):
  1652. spec_or_id = {"_id": spec_or_id}
  1653. write_concern = None
  1654. if kwargs:
  1655. write_concern = WriteConcern(**kwargs)
  1656. with self._socket_for_writes() as sock_info:
  1657. return self._delete(sock_info, spec_or_id, multi, write_concern)
  1658. def find_and_modify(self, query={}, update=None,
  1659. upsert=False, sort=None, full_response=False,
  1660. manipulate=False, **kwargs):
  1661. """Update and return an object.
  1662. **DEPRECATED** - Use :meth:`find_one_and_delete`,
  1663. :meth:`find_one_and_replace`, or :meth:`find_one_and_update` instead.
  1664. """
  1665. warnings.warn("find_and_modify is deprecated, use find_one_and_delete"
  1666. ", find_one_and_replace, or find_one_and_update instead",
  1667. DeprecationWarning, stacklevel=2)
  1668. if not update and not kwargs.get('remove', None):
  1669. raise ValueError("Must either update or remove")
  1670. if update and kwargs.get('remove', None):
  1671. raise ValueError("Can't do both update and remove")
  1672. # No need to include empty args
  1673. if query:
  1674. kwargs['query'] = query
  1675. if update:
  1676. kwargs['update'] = update
  1677. if upsert:
  1678. kwargs['upsert'] = upsert
  1679. if sort:
  1680. # Accept a list of tuples to match Cursor's sort parameter.
  1681. if isinstance(sort, list):
  1682. kwargs['sort'] = helpers._index_document(sort)
  1683. # Accept OrderedDict, SON, and dict with len == 1 so we
  1684. # don't break existing code already using find_and_modify.
  1685. elif (isinstance(sort, _ORDERED_TYPES) or
  1686. isinstance(sort, dict) and len(sort) == 1):
  1687. warnings.warn("Passing mapping types for `sort` is deprecated,"
  1688. " use a list of (key, direction) pairs instead",
  1689. DeprecationWarning, stacklevel=2)
  1690. kwargs['sort'] = sort
  1691. else:
  1692. raise TypeError("sort must be a list of (key, direction) "
  1693. "pairs, a dict of len 1, or an instance of "
  1694. "SON or OrderedDict")
  1695. fields = kwargs.pop("fields", None)
  1696. if fields is not None:
  1697. kwargs["fields"] = helpers._fields_list_to_dict(fields, "fields")
  1698. cmd = SON([("findAndModify", self.__name)])
  1699. cmd.update(kwargs)
  1700. with self._socket_for_writes() as sock_info:
  1701. out = self._command(sock_info, cmd,
  1702. read_preference=ReadPreference.PRIMARY,
  1703. allowable_errors=[_NO_OBJ_ERROR])
  1704. if not out['ok']:
  1705. if out["errmsg"] == _NO_OBJ_ERROR:
  1706. return None
  1707. else:
  1708. # Should never get here b/c of allowable_errors
  1709. raise ValueError("Unexpected Error: %s" % (out,))
  1710. if full_response:
  1711. return out
  1712. else:
  1713. document = out.get('value')
  1714. if manipulate:
  1715. document = self.__database._fix_outgoing(document, self)
  1716. return document
  1717. def __iter__(self):
  1718. return self
  1719. def __next__(self):
  1720. raise TypeError("'Collection' object is not iterable")
  1721. next = __next__
  1722. def __call__(self, *args, **kwargs):
  1723. """This is only here so that some API misusages are easier to debug.
  1724. """
  1725. if "." not in self.__name:
  1726. raise TypeError("'Collection' object is not callable. If you "
  1727. "meant to call the '%s' method on a 'Database' "
  1728. "object it is failing because no such method "
  1729. "exists." %
  1730. self.__name)
  1731. raise TypeError("'Collection' object is not callable. If you meant to "
  1732. "call the '%s' method on a 'Collection' object it is "
  1733. "failing because no such method exists." %
  1734. self.__name.split(".")[-1])