MongoCollection.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. use Alcaeus\MongoDbAdapter\TypeConverter;
  16. /**
  17. * Represents a database collection.
  18. * @link http://www.php.net/manual/en/class.mongocollection.php
  19. */
  20. class MongoCollection
  21. {
  22. const ASCENDING = 1;
  23. const DESCENDING = -1;
  24. /**
  25. * @var MongoDB
  26. */
  27. public $db = NULL;
  28. /**
  29. * @var string
  30. */
  31. protected $name;
  32. /**
  33. * @var \MongoDB\Collection
  34. */
  35. protected $collection;
  36. /**
  37. * @var int<p>
  38. */
  39. public $w;
  40. /**
  41. * @var int <p>
  42. */
  43. public $wtimeout;
  44. /**
  45. * Creates a new collection
  46. * @link http://www.php.net/manual/en/mongocollection.construct.php
  47. * @param MongoDB $db Parent database.
  48. * @param string $name Name for this collection.
  49. * @throws Exception
  50. * @return MongoCollection
  51. */
  52. public function __construct(MongoDB $db, $name)
  53. {
  54. $this->db = $db;
  55. $this->name = $name;
  56. $this->collection = $this->db->getDb()->selectCollection($name);
  57. }
  58. /**
  59. * Gets the underlying collection for this object
  60. *
  61. * @internal This part is not of the ext-mongo API and should not be used
  62. * @return \MongoDB\Collection
  63. */
  64. public function getCollection()
  65. {
  66. return $this->collection;
  67. }
  68. /**
  69. * String representation of this collection
  70. * @link http://www.php.net/manual/en/mongocollection.--tostring.php
  71. * @return string Returns the full name of this collection.
  72. */
  73. public function __toString()
  74. {
  75. return (string) $this->db . '.' . $this->name;
  76. }
  77. /**
  78. * Gets a collection
  79. * @link http://www.php.net/manual/en/mongocollection.get.php
  80. * @param string $name The next string in the collection name.
  81. * @return MongoCollection
  82. */
  83. public function __get($name)
  84. {
  85. return $this->db->selectCollection($this->name . '.' . $name);
  86. }
  87. /**
  88. * @link http://www.php.net/manual/en/mongocollection.aggregate.php
  89. * @param array $pipeline
  90. * @param array $op
  91. * @param array $pipelineOperators
  92. * @return array
  93. */
  94. public function aggregate(array $pipeline, array $op, array $pipelineOperators)
  95. {
  96. $this->notImplemented();
  97. }
  98. /**
  99. * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
  100. * @param array $pipeline
  101. * @param array $options
  102. * @return MongoCommandCursor
  103. */
  104. public function aggregateCursor(array $pipeline, array $options)
  105. {
  106. return $this->collection->aggregate($pipeline, $options);
  107. }
  108. /**
  109. * Returns this collection's name
  110. * @link http://www.php.net/manual/en/mongocollection.getname.php
  111. * @return string
  112. */
  113. public function getName()
  114. {
  115. return $this->name;
  116. }
  117. /**
  118. * @link http://www.php.net/manual/en/mongocollection.getslaveokay.php
  119. * @return bool
  120. */
  121. public function getSlaveOkay()
  122. {
  123. $this->notImplemented();
  124. }
  125. /**
  126. * @link http://www.php.net/manual/en/mongocollection.setslaveokay.php
  127. * @param bool $ok
  128. * @return bool
  129. */
  130. public function setSlaveOkay($ok = true)
  131. {
  132. $this->notImplemented();
  133. }
  134. /**
  135. * @link http://www.php.net/manual/en/mongocollection.getreadpreference.php
  136. * @return array
  137. */
  138. public function getReadPreference()
  139. {
  140. $this->notImplemented();
  141. }
  142. /**
  143. * @param string $read_preference
  144. * @param array $tags
  145. * @return bool
  146. */
  147. public function setReadPreference($read_preference, array $tags)
  148. {
  149. $this->notImplemented();
  150. }
  151. /**
  152. * Drops this collection
  153. * @link http://www.php.net/manual/en/mongocollection.drop.php
  154. * @return array Returns the database response.
  155. */
  156. public function drop()
  157. {
  158. return $this->collection->drop();
  159. }
  160. /**
  161. * Validates this collection
  162. * @link http://www.php.net/manual/en/mongocollection.validate.php
  163. * @param bool $scan_data Only validate indices, not the base collection.
  164. * @return array Returns the database's evaluation of this object.
  165. */
  166. public function validate($scan_data = FALSE)
  167. {
  168. $this->notImplemented();
  169. }
  170. /**
  171. * Inserts an array into the collection
  172. * @link http://www.php.net/manual/en/mongocollection.insert.php
  173. * @param array|object $a
  174. * @param array $options
  175. * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
  176. * @throws MongoCursorException if the "w" option is set and the write fails.
  177. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
  178. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
  179. */
  180. public function insert($a, array $options = array())
  181. {
  182. return $this->collection->insertOne(TypeConverter::convertLegacyArrayToObject($a), $options);
  183. }
  184. /**
  185. * Inserts multiple documents into this collection
  186. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  187. * @param array $a An array of arrays.
  188. * @param array $options Options for the inserts.
  189. * @throws MongoCursorException
  190. * @return mixed f "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.
  191. */
  192. public function batchInsert(array $a, array $options = array())
  193. {
  194. return $this->collection->insertMany($a, $options);
  195. }
  196. /**
  197. * Update records based on a given criteria
  198. * @link http://www.php.net/manual/en/mongocollection.update.php
  199. * @param array $criteria Description of the objects to update.
  200. * @param array $newobj The object with which to update the matching records.
  201. * @param array $options This parameter is an associative array of the form
  202. * array("optionname" => boolean, ...).
  203. *
  204. * Currently supported options are:
  205. * "upsert": If no document matches $$criteria, a new document will be created from $$criteria and $$new_object (see upsert example).
  206. *
  207. * "multiple": All documents matching $criteria will be updated. MongoCollection::update has exactly the opposite behavior of MongoCollection::remove- it updates one document by
  208. * default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the
  209. * database may change its default behavior at some point in the future.
  210. *
  211. * "safe" Can be a boolean or integer, defaults to false. If false, the program continues executing without waiting for a database response. If true, the program will wait for
  212. * the database response and throw a MongoCursorException if the update did not succeed. If you are using replication and the master has changed, using "safe" will make the driver
  213. * disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).
  214. * If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.
  215. * If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout).
  216. * This overrides the w variable set on the collection.
  217. *
  218. * "fsync": Boolean, defaults to false. Forces the update to be synced to disk before returning success. If true, a safe update is implied and will override setting safe to false.
  219. *
  220. * "timeout" Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does
  221. * not respond within the timeout period, a MongoCursorTimeoutException will be thrown
  222. * @throws MongoCursorException
  223. * @return boolean
  224. */
  225. public function update(array $criteria , array $newobj, array $options = array())
  226. {
  227. $multiple = ($options['multiple']) ? $options['multiple'] : false;
  228. // $multiple = $options['multiple'] ?? false;
  229. $method = $multiple ? 'updateMany' : 'updateOne';
  230. return $this->collection->$method($criteria, $newobj, $options);
  231. }
  232. /**
  233. * (PECL mongo &gt;= 0.9.0)<br/>
  234. * Remove records from this collection
  235. * @link http://www.php.net/manual/en/mongocollection.remove.php
  236. * @param array $criteria [optional] <p>Query criteria for the documents to delete.</p>
  237. * @param array $options [optional] <p>An array of options for the remove operation. Currently available options
  238. * include:
  239. * </p><ul>
  240. * <li><p><em>"w"</em></p><p>See {@link http://www.php.net/manual/en/mongo.writeconcerns.php Write Concerns}. The default value for <b>MongoClient</b> is <em>1</em>.</p></li>
  241. * <li>
  242. * <p>
  243. * <em>"justOne"</em>
  244. * </p>
  245. * <p>
  246. * Specify <strong><code>TRUE</code></strong> to limit deletion to just one document. If <strong><code>FALSE</code></strong> or
  247. * omitted, all documents matching the criteria will be deleted.
  248. * </p>
  249. * </li>
  250. * <li><p><em>"fsync"</em></p><p>Boolean, defaults to <b>FALSE</b>. If journaling is enabled, it works exactly like <em>"j"</em>. If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If <strong><code>TRUE</code></strong>, an acknowledged insert is implied and this option will override setting <em>"w"</em> to <em>0</em>.</p><blockquote class="note"><p><strong class="note">Note</strong>: <span class="simpara">If journaling is enabled, users are strongly encouraged to use the <em>"j"</em> option instead of <em>"fsync"</em>. Do not use <em>"fsync"</em> and <em>"j"</em> simultaneously, as that will result in an error.</p></blockquote></li>
  251. * <li><p><em>"j"</em></p><p>Boolean, defaults to <b>FALSE</b>. Forces the write operation to block until it is synced to the journal on disk. If <strong><code>TRUE</code></strong>, an acknowledged write is implied and this option will override setting <em>"w"</em> to <em>0</em>.</p><blockquote class="note"><p><strong class="note">Note</strong>: <span class="simpara">If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.</p></blockquote></li>
  252. * <li><p><em>"socketTimeoutMS"</em></p><p>This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a <b>MongoCursorTimeoutException</b> will be thrown and there will be no way to determine if the server actually handled the write or not. A value of <em>-1</em> may be specified to block indefinitely. The default value for <b>MongoClient</b> is <em>30000</em> (30 seconds).</p></li>
  253. * <li><p><em>"w"</em></p><p>See {@link http://www.php.net/manual/en/mongo.writeconcerns.php Write Concerns }. The default value for <b>MongoClient</b> is <em>1</em>.</p></li>
  254. * <li><p><em>"wTimeoutMS"</em></p><p>This option specifies the time limit, in milliseconds, for {@link http://www.php.net/manual/en/mongo.writeconcerns.php write concern} acknowledgement. It is only applicable when <em>"w"</em> is greater than <em>1</em>, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a <a href="class.mongocursorexception.php" class="classname">MongoCursorException</a> will be thrown. A value of <em>0</em> may be specified to block indefinitely. The default value for {@link http://www.php.net/manual/en/class.mongoclient.php MongoClient} is <em>10000</em> (ten seconds).</p></li>
  255. * </ul>
  256. *
  257. * <p>
  258. * The following options are deprecated and should no longer be used:
  259. * </p><ul>
  260. * <li><p><em>"safe"</em></p><p>Deprecated. Please use the {@link http://www.php.net/manual/en/mongo.writeconcerns.php write concern} <em>"w"</em> option.</p></li>
  261. * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
  262. * <li><p><b>"wtimeout"</b></p><p>Deprecated alias for <em>"wTimeoutMS"</em>.</p></p>
  263. * @throws MongoCursorException
  264. * @throws MongoCursorTimeoutException
  265. * @return bool|array <p>Returns an array containing the status of the removal if the
  266. * <em>"w"</em> option is set. Otherwise, returns <b>TRUE</b>.
  267. * </p>
  268. * <p>
  269. * Fields in the status array are described in the documentation for
  270. * <b>MongoCollection::insert()</b>.
  271. * </p>
  272. */
  273. public function remove(array $criteria = array(), array $options = array())
  274. {
  275. $multiple = isset($options['justOne']) ? !$options['justOne'] : false;
  276. // $multiple = !$options['justOne'] ?? false;
  277. $method = $multiple ? 'deleteMany' : 'deleteOne';
  278. return $this->collection->$method($criteria, $options);
  279. }
  280. /**
  281. * Querys this collection
  282. * @link http://www.php.net/manual/en/mongocollection.find.php
  283. * @param array $query The fields for which to search.
  284. * @param array $fields Fields of the results to return.
  285. * @return MongoCursor
  286. */
  287. public function find(array $query = array(), array $fields = array())
  288. {
  289. $cursor = $this->collection->find($query);
  290. return new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields, $cursor);
  291. }
  292. /**
  293. * Retrieve a list of distinct values for the given key across a collection
  294. * @link http://www.php.net/manual/ru/mongocollection.distinct.php
  295. * @param string $key The key to use.
  296. * @param array $query An optional query parameters
  297. * @return array|bool Returns an array of distinct values, or <b>FALSE</b> on failure
  298. */
  299. public function distinct($key, array $query = NULL)
  300. {
  301. return array_map([TypeConverter::class, 'convertToLegacyType'], $this->collection->distinct($key, $query));
  302. }
  303. /**
  304. * Update a document and return it
  305. * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
  306. * @param array $query The query criteria to search for.
  307. * @param array $update The update criteria.
  308. * @param array $fields Optionally only return these fields.
  309. * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
  310. * @return array Returns the original document, or the modified document when new is set.
  311. */
  312. public function findAndModify(array $query, array $update = NULL, array $fields = NULL, array $options = NULL)
  313. {
  314. }
  315. /**
  316. * Querys this collection, returning a single element
  317. * @link http://www.php.net/manual/en/mongocollection.findone.php
  318. * @param array $query The fields for which to search.
  319. * @param array $fields Fields of the results to return.
  320. * @return array|null
  321. */
  322. public function findOne(array $query = array(), array $fields = array())
  323. {
  324. $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query));
  325. if ($document !== null) {
  326. $document = TypeConverter::convertObjectToLegacyArray($document);
  327. }
  328. return $document;
  329. }
  330. /**
  331. * Creates an index on the given field(s), or does nothing if the index already exists
  332. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  333. * @param array $keys Field or fields to use as index.
  334. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  335. * @return array Returns the database response.
  336. */
  337. public function createIndex(array $keys, array $options = array()) {}
  338. /**
  339. * @deprecated Use MongoCollection::createIndex() instead.
  340. * Creates an index on the given field(s), or does nothing if the index already exists
  341. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  342. * @param array $keys Field or fields to use as index.
  343. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  344. * @return boolean always true
  345. */
  346. public function ensureIndex(array $keys, array $options = array()) {}
  347. /**
  348. * Deletes an index from this collection
  349. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  350. * @param string|array $keys Field or fields from which to delete the index.
  351. * @return array Returns the database response.
  352. */
  353. public function deleteIndex($keys) {}
  354. /**
  355. * Delete all indexes for this collection
  356. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  357. * @return array Returns the database response.
  358. */
  359. public function deleteIndexes() {}
  360. /**
  361. * Returns an array of index names for this collection
  362. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  363. * @return array Returns a list of index names.
  364. */
  365. public function getIndexInfo() {}
  366. /**
  367. * Counts the number of documents in this collection
  368. * @link http://www.php.net/manual/en/mongocollection.count.php
  369. * @param array|stdClass $query
  370. * @return int Returns the number of documents matching the query.
  371. */
  372. public function count($query = array())
  373. {
  374. return $this->collection->count($query);
  375. }
  376. /**
  377. * Saves an object to this collection
  378. * @link http://www.php.net/manual/en/mongocollection.save.php
  379. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  380. * Note: If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it.
  381. * See MongoCollection::insert() for additional information on this behavior.
  382. * @param array $options Options for the save.
  383. * <dl>
  384. * <dt>"w"
  385. * <dd>See WriteConcerns. The default value for MongoClient is 1.
  386. * <dt>"fsync"
  387. * <dd>Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, an acknowledged insert is implied and will override setting w to 0.
  388. * <dt>"timeout"
  389. * <dd>Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.
  390. * <dt>"safe"
  391. * <dd>Deprecated. Please use the WriteConcern w option.
  392. * </dl>
  393. * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
  394. * @throws MongoCursorException if the "w" option is set and the write fails.
  395. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
  396. * @return array|boolean If w was set, returns an array containing the status of the save.
  397. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  398. */
  399. public function save($a, array $options = array()) {}
  400. /**
  401. * Creates a database reference
  402. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  403. * @param array $a Object to which to create a reference.
  404. * @return array Returns a database reference array.
  405. */
  406. public function createDBRef(array $a) {}
  407. /**
  408. * Fetches the document pointed to by a database reference
  409. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  410. * @param array $ref A database reference.
  411. * @return array Returns the database document pointed to by the reference.
  412. */
  413. public function getDBRef(array $ref) {}
  414. /**
  415. * @param mixed $keys
  416. * @static
  417. * @return string
  418. */
  419. protected static function toIndexString($keys) {}
  420. /**
  421. * Performs an operation similar to SQL's GROUP BY command
  422. * @link http://www.php.net/manual/en/mongocollection.group.php
  423. * @param mixed $keys Fields to group by. If an array or non-code object is passed, it will be the key used to group results.
  424. * @param array $initial Initial value of the aggregation counter object.
  425. * @param MongoCode $reduce A function that aggregates (reduces) the objects iterated.
  426. * @param array $condition An condition that must be true for a row to be considered.
  427. * @return array
  428. */
  429. public function group($keys, array $initial, MongoCode $reduce, array $condition = array()) {}
  430. protected function notImplemented()
  431. {
  432. throw new \Exception('Not implemented');
  433. }
  434. }