operations.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright 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. """Operation class definitions."""
  15. from pymongo.common import validate_boolean, validate_is_mapping
  16. from pymongo.helpers import _gen_index_name, _index_document, _index_list
  17. class _WriteOp(object):
  18. """Private base class for all write operations."""
  19. __slots__ = ("_filter", "_doc", "_upsert")
  20. def __init__(self, filter=None, doc=None, upsert=None):
  21. if filter is not None:
  22. validate_is_mapping("filter", filter)
  23. if upsert is not None:
  24. validate_boolean("upsert", upsert)
  25. self._filter = filter
  26. self._doc = doc
  27. self._upsert = upsert
  28. class InsertOne(_WriteOp):
  29. """Represents an insert_one operation."""
  30. def __init__(self, document):
  31. """Create an InsertOne instance.
  32. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  33. :Parameters:
  34. - `document`: The document to insert. If the document is missing an
  35. _id field one will be added.
  36. """
  37. super(InsertOne, self).__init__(doc=document)
  38. def _add_to_bulk(self, bulkobj):
  39. """Add this operation to the _Bulk instance `bulkobj`."""
  40. bulkobj.add_insert(self._doc)
  41. def __repr__(self):
  42. return "InsertOne(%r)" % (self._doc,)
  43. class DeleteOne(_WriteOp):
  44. """Represents a delete_one operation."""
  45. def __init__(self, filter):
  46. """Create a DeleteOne instance.
  47. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  48. :Parameters:
  49. - `filter`: A query that matches the document to delete.
  50. """
  51. super(DeleteOne, self).__init__(filter)
  52. def _add_to_bulk(self, bulkobj):
  53. """Add this operation to the _Bulk instance `bulkobj`."""
  54. bulkobj.add_delete(self._filter, 1)
  55. def __repr__(self):
  56. return "DeleteOne(%r)" % (self._filter,)
  57. class DeleteMany(_WriteOp):
  58. """Represents a delete_many operation."""
  59. def __init__(self, filter):
  60. """Create a DeleteMany instance.
  61. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  62. :Parameters:
  63. - `filter`: A query that matches the documents to delete.
  64. """
  65. super(DeleteMany, self).__init__(filter)
  66. def _add_to_bulk(self, bulkobj):
  67. """Add this operation to the _Bulk instance `bulkobj`."""
  68. bulkobj.add_delete(self._filter, 0)
  69. def __repr__(self):
  70. return "DeleteMany(%r)" % (self._filter,)
  71. class ReplaceOne(_WriteOp):
  72. """Represents a replace_one operation."""
  73. def __init__(self, filter, replacement, upsert=False):
  74. """Create a ReplaceOne instance.
  75. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  76. :Parameters:
  77. - `filter`: A query that matches the document to replace.
  78. - `replacement`: The new document.
  79. - `upsert` (optional): If ``True``, perform an insert if no documents
  80. match the filter.
  81. """
  82. super(ReplaceOne, self).__init__(filter, replacement, upsert)
  83. def _add_to_bulk(self, bulkobj):
  84. """Add this operation to the _Bulk instance `bulkobj`."""
  85. bulkobj.add_replace(self._filter, self._doc, self._upsert)
  86. def __repr__(self):
  87. return "ReplaceOne(%r, %r, %r)" % (self._filter,
  88. self._doc,
  89. self._upsert)
  90. class UpdateOne(_WriteOp):
  91. """Represents an update_one operation."""
  92. def __init__(self, filter, update, upsert=False):
  93. """Represents an update_one operation.
  94. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  95. :Parameters:
  96. - `filter`: A query that matches the document to update.
  97. - `update`: The modifications to apply.
  98. - `upsert` (optional): If ``True``, perform an insert if no documents
  99. match the filter.
  100. """
  101. super(UpdateOne, self).__init__(filter, update, upsert)
  102. def _add_to_bulk(self, bulkobj):
  103. """Add this operation to the _Bulk instance `bulkobj`."""
  104. bulkobj.add_update(self._filter, self._doc, False, self._upsert)
  105. def __repr__(self):
  106. return "UpdateOne(%r, %r, %r)" % (self._filter,
  107. self._doc,
  108. self._upsert)
  109. class UpdateMany(_WriteOp):
  110. """Represents an update_many operation."""
  111. def __init__(self, filter, update, upsert=False):
  112. """Create an UpdateMany instance.
  113. For use with :meth:`~pymongo.collection.Collection.bulk_write`.
  114. :Parameters:
  115. - `filter`: A query that matches the documents to update.
  116. - `update`: The modifications to apply.
  117. - `upsert` (optional): If ``True``, perform an insert if no documents
  118. match the filter.
  119. """
  120. super(UpdateMany, self).__init__(filter, update, upsert)
  121. def _add_to_bulk(self, bulkobj):
  122. """Add this operation to the _Bulk instance `bulkobj`."""
  123. bulkobj.add_update(self._filter, self._doc, True, self._upsert)
  124. def __repr__(self):
  125. return "UpdateMany(%r, %r, %r)" % (self._filter,
  126. self._doc,
  127. self._upsert)
  128. class IndexModel(object):
  129. """Represents an index to create."""
  130. __slots__ = ("__document",)
  131. def __init__(self, keys, **kwargs):
  132. """Create an Index instance.
  133. For use with :meth:`~pymongo.collection.Collection.create_indexes`.
  134. Takes either a single key or a list of (key, direction) pairs.
  135. The key(s) must be an instance of :class:`basestring`
  136. (:class:`str` in python 3), and the direction(s) must be one of
  137. (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
  138. :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOHAYSTACK`,
  139. :data:`~pymongo.GEOSPHERE`, :data:`~pymongo.HASHED`,
  140. :data:`~pymongo.TEXT`).
  141. Valid options include, but are not limited to:
  142. - `name`: custom name to use for this index - if none is
  143. given, a name will be generated.
  144. - `unique`: if ``True`` creates a uniqueness constraint on the index.
  145. - `background`: if ``True`` this index should be created in the
  146. background.
  147. - `sparse`: if ``True``, omit from the index any documents that lack
  148. the indexed field.
  149. - `bucketSize`: for use with geoHaystack indexes.
  150. Number of documents to group together within a certain proximity
  151. to a given longitude and latitude.
  152. - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
  153. index.
  154. - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
  155. index.
  156. - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
  157. collection. MongoDB will automatically delete documents from
  158. this collection after <int> seconds. The indexed field must
  159. be a UTC datetime or the data will not expire.
  160. See the MongoDB documentation for a full list of supported options by
  161. server version.
  162. :Parameters:
  163. - `keys`: a single key or a list of (key, direction)
  164. pairs specifying the index to create
  165. - `**kwargs` (optional): any additional index creation
  166. options (see the above list) should be passed as keyword
  167. arguments
  168. """
  169. keys = _index_list(keys)
  170. if "name" not in kwargs:
  171. kwargs["name"] = _gen_index_name(keys)
  172. kwargs["key"] = _index_document(keys)
  173. self.__document = kwargs
  174. @property
  175. def document(self):
  176. """An index document suitable for passing to the createIndexes
  177. command.
  178. """
  179. return self.__document