MongoCollection.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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. if (class_exists('MongoCollection', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\Helper;
  19. use Alcaeus\MongoDbAdapter\TypeConverter;
  20. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  21. /**
  22. * Represents a database collection.
  23. * @link http://www.php.net/manual/en/class.mongocollection.php
  24. */
  25. class MongoCollection
  26. {
  27. use Helper\ReadPreference;
  28. use Helper\SlaveOkay;
  29. use Helper\WriteConcern;
  30. const ASCENDING = 1;
  31. const DESCENDING = -1;
  32. /**
  33. * @var MongoDB
  34. */
  35. public $db = null;
  36. /**
  37. * @var string
  38. */
  39. protected $name;
  40. /**
  41. * @var \MongoDB\Collection
  42. */
  43. protected $collection;
  44. /**
  45. * Creates a new collection
  46. *
  47. * @link http://www.php.net/manual/en/mongocollection.construct.php
  48. * @param MongoDB $db Parent database.
  49. * @param string $name Name for this collection.
  50. * @throws Exception
  51. */
  52. public function __construct(MongoDB $db, $name)
  53. {
  54. $this->checkCollectionName($name);
  55. $this->db = $db;
  56. $this->name = (string) $name;
  57. $this->setReadPreferenceFromArray($db->getReadPreference());
  58. $this->setWriteConcernFromArray($db->getWriteConcern());
  59. $this->createCollectionObject();
  60. }
  61. /**
  62. * Gets the underlying collection for this object
  63. *
  64. * @internal This part is not of the ext-mongo API and should not be used
  65. * @return \MongoDB\Collection
  66. */
  67. public function getCollection()
  68. {
  69. return $this->collection;
  70. }
  71. /**
  72. * String representation of this collection
  73. *
  74. * @link http://www.php.net/manual/en/mongocollection.--tostring.php
  75. * @return string Returns the full name of this collection.
  76. */
  77. public function __toString()
  78. {
  79. return (string) $this->db . '.' . $this->name;
  80. }
  81. /**
  82. * Gets a collection
  83. *
  84. * @link http://www.php.net/manual/en/mongocollection.get.php
  85. * @param string $name The next string in the collection name.
  86. * @return MongoCollection
  87. */
  88. public function __get($name)
  89. {
  90. // Handle w and wtimeout properties that replicate data stored in $readPreference
  91. if ($name === 'w' || $name === 'wtimeout') {
  92. return $this->getWriteConcern()[$name];
  93. }
  94. return $this->db->selectCollection($this->name . '.' . str_replace(chr(0), '', $name));
  95. }
  96. /**
  97. * @param string $name
  98. * @param mixed $value
  99. */
  100. public function __set($name, $value)
  101. {
  102. if ($name === 'w' || $name === 'wtimeout') {
  103. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  104. $this->createCollectionObject();
  105. }
  106. }
  107. /**
  108. * Perform an aggregation using the aggregation framework
  109. *
  110. * @link http://www.php.net/manual/en/mongocollection.aggregate.php
  111. * @param array $pipeline
  112. * @param array $op
  113. * @return array
  114. */
  115. public function aggregate(array $pipeline, array $op = [])
  116. {
  117. if (! TypeConverter::isNumericArray($pipeline)) {
  118. $operators = func_get_args();
  119. $pipeline = [];
  120. $options = [];
  121. $i = 0;
  122. foreach ($operators as $operator) {
  123. $i++;
  124. if (! is_array($operator)) {
  125. trigger_error("Argument $i is not an array", E_USER_WARNING);
  126. return;
  127. }
  128. $pipeline[] = $operator;
  129. }
  130. } else {
  131. $options = $op;
  132. }
  133. if (isset($options['cursor'])) {
  134. $options['useCursor'] = true;
  135. if (isset($options['cursor']['batchSize'])) {
  136. $options['batchSize'] = $options['cursor']['batchSize'];
  137. }
  138. unset($options['cursor']);
  139. } else {
  140. $options['useCursor'] = false;
  141. }
  142. try {
  143. $cursor = $this->collection->aggregate(TypeConverter::fromLegacy($pipeline), $options);
  144. return [
  145. 'ok' => 1.0,
  146. 'result' => TypeConverter::toLegacy($cursor),
  147. 'waitedMS' => 0,
  148. ];
  149. } catch (\MongoDB\Driver\Exception\Exception $e) {
  150. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  151. }
  152. }
  153. /**
  154. * Execute an aggregation pipeline command and retrieve results through a cursor
  155. *
  156. * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
  157. * @param array $pipeline
  158. * @param array $options
  159. * @return MongoCommandCursor
  160. */
  161. public function aggregateCursor(array $pipeline, array $options = [])
  162. {
  163. // Build command manually, can't use mongo-php-library here
  164. $command = [
  165. 'aggregate' => $this->name,
  166. 'pipeline' => $pipeline
  167. ];
  168. // Convert cursor option
  169. if (! isset($options['cursor'])) {
  170. $options['cursor'] = new \stdClass();
  171. }
  172. $command += $options;
  173. $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
  174. $cursor->setReadPreference($this->getReadPreference());
  175. return $cursor;
  176. }
  177. /**
  178. * Returns this collection's name
  179. *
  180. * @link http://www.php.net/manual/en/mongocollection.getname.php
  181. * @return string
  182. */
  183. public function getName()
  184. {
  185. return $this->name;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function setReadPreference($readPreference, $tags = null)
  191. {
  192. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  193. $this->createCollectionObject();
  194. return $result;
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function setWriteConcern($wstring, $wtimeout = 0)
  200. {
  201. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  202. $this->createCollectionObject();
  203. return $result;
  204. }
  205. /**
  206. * Drops this collection
  207. *
  208. * @link http://www.php.net/manual/en/mongocollection.drop.php
  209. * @return array Returns the database response.
  210. */
  211. public function drop()
  212. {
  213. return TypeConverter::toLegacy($this->collection->drop());
  214. }
  215. /**
  216. * Validates this collection
  217. *
  218. * @link http://www.php.net/manual/en/mongocollection.validate.php
  219. * @param bool $scan_data Only validate indices, not the base collection.
  220. * @return array Returns the database's evaluation of this object.
  221. */
  222. public function validate($scan_data = false)
  223. {
  224. $command = [
  225. 'validate' => $this->name,
  226. 'full' => $scan_data,
  227. ];
  228. return $this->db->command($command);
  229. }
  230. /**
  231. * Inserts an array into the collection
  232. *
  233. * @link http://www.php.net/manual/en/mongocollection.insert.php
  234. * @param array|object $a
  235. * @param array $options
  236. * @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.
  237. * @throws MongoCursorException if the "w" option is set and the write fails.
  238. * @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.
  239. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
  240. */
  241. public function insert(&$a, array $options = [])
  242. {
  243. if (! $this->ensureDocumentHasMongoId($a)) {
  244. trigger_error(sprintf('%s(): expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  245. return;
  246. }
  247. if (! count((array)$a)) {
  248. throw new \MongoException('document must be an array or object');
  249. }
  250. try {
  251. $result = $this->collection->insertOne(
  252. TypeConverter::fromLegacy($a),
  253. $this->convertWriteConcernOptions($options)
  254. );
  255. } catch (\MongoDB\Driver\Exception\Exception $e) {
  256. throw ExceptionConverter::toLegacy($e);
  257. }
  258. if (! $result->isAcknowledged()) {
  259. return true;
  260. }
  261. return [
  262. 'ok' => 1.0,
  263. 'n' => 0,
  264. 'err' => null,
  265. 'errmsg' => null,
  266. ];
  267. }
  268. /**
  269. * Inserts multiple documents into this collection
  270. *
  271. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  272. * @param array $a An array of arrays.
  273. * @param array $options Options for the inserts.
  274. * @throws MongoCursorException
  275. * @return mixed If "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.
  276. */
  277. public function batchInsert(array &$a, array $options = [])
  278. {
  279. if (empty($a)) {
  280. throw new \MongoException('No write ops were included in the batch');
  281. }
  282. $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
  283. foreach ($a as $key => $item) {
  284. try {
  285. if (! $this->ensureDocumentHasMongoId($a[$key])) {
  286. if ($continueOnError) {
  287. unset($a[$key]);
  288. } else {
  289. trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  290. return;
  291. }
  292. }
  293. } catch (MongoException $e) {
  294. if (! $continueOnError) {
  295. throw $e;
  296. }
  297. }
  298. }
  299. try {
  300. $result = $this->collection->insertMany(
  301. TypeConverter::fromLegacy(array_values($a)),
  302. $this->convertWriteConcernOptions($options)
  303. );
  304. } catch (\MongoDB\Driver\Exception\Exception $e) {
  305. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  306. }
  307. if (! $result->isAcknowledged()) {
  308. return true;
  309. }
  310. return [
  311. 'ok' => 1.0,
  312. 'connectionId' => 0,
  313. 'n' => 0,
  314. 'syncMillis' => 0,
  315. 'writtenTo' => null,
  316. 'err' => null,
  317. ];
  318. }
  319. /**
  320. * Update records based on a given criteria
  321. *
  322. * @link http://www.php.net/manual/en/mongocollection.update.php
  323. * @param array $criteria Description of the objects to update.
  324. * @param array $newobj The object with which to update the matching records.
  325. * @param array $options
  326. * @throws MongoCursorException
  327. * @return boolean
  328. */
  329. public function update(array $criteria, array $newobj, array $options = [])
  330. {
  331. $multiple = isset($options['multiple']) ? $options['multiple'] : false;
  332. $isReplace = ! \MongoDB\is_first_key_operator($newobj);
  333. if ($isReplace && $multiple) {
  334. throw new \MongoWriteConcernException('multi update only works with $ operators', 9);
  335. }
  336. unset($options['multiple']);
  337. $method = $isReplace ? 'replace' : 'update';
  338. $method .= $multiple ? 'Many' : 'One';
  339. try {
  340. /** @var \MongoDB\UpdateResult $result */
  341. $result = $this->collection->$method(
  342. TypeConverter::fromLegacy($criteria),
  343. TypeConverter::fromLegacy($newobj),
  344. $this->convertWriteConcernOptions($options)
  345. );
  346. } catch (\MongoDB\Driver\Exception\Exception $e) {
  347. throw ExceptionConverter::toLegacy($e);
  348. }
  349. if (! $result->isAcknowledged()) {
  350. return true;
  351. }
  352. return [
  353. 'ok' => 1.0,
  354. 'nModified' => $result->getModifiedCount(),
  355. 'n' => $result->getMatchedCount(),
  356. 'err' => null,
  357. 'errmsg' => null,
  358. 'updatedExisting' => $result->getUpsertedCount() == 0,
  359. ];
  360. }
  361. /**
  362. * Remove records from this collection
  363. *
  364. * @link http://www.php.net/manual/en/mongocollection.remove.php
  365. * @param array $criteria Query criteria for the documents to delete.
  366. * @param array $options An array of options for the remove operation.
  367. * @throws MongoCursorException
  368. * @throws MongoCursorTimeoutException
  369. * @return bool|array Returns an array containing the status of the removal
  370. * if the "w" option is set. Otherwise, returns TRUE.
  371. */
  372. public function remove(array $criteria = [], array $options = [])
  373. {
  374. $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
  375. $method = $multiple ? 'deleteMany' : 'deleteOne';
  376. try {
  377. /** @var \MongoDB\DeleteResult $result */
  378. $result = $this->collection->$method(
  379. TypeConverter::fromLegacy($criteria),
  380. $this->convertWriteConcernOptions($options)
  381. );
  382. } catch (\MongoDB\Driver\Exception\Exception $e) {
  383. throw ExceptionConverter::toLegacy($e);
  384. }
  385. if (! $result->isAcknowledged()) {
  386. return true;
  387. }
  388. return [
  389. 'ok' => 1.0,
  390. 'n' => $result->getDeletedCount(),
  391. 'err' => null,
  392. 'errmsg' => null
  393. ];
  394. }
  395. /**
  396. * Querys this collection
  397. *
  398. * @link http://www.php.net/manual/en/mongocollection.find.php
  399. * @param array $query The fields for which to search.
  400. * @param array $fields Fields of the results to return.
  401. * @return MongoCursor
  402. */
  403. public function find(array $query = [], array $fields = [])
  404. {
  405. $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
  406. $cursor->setReadPreference($this->getReadPreference());
  407. return $cursor;
  408. }
  409. /**
  410. * Retrieve a list of distinct values for the given key across a collection
  411. *
  412. * @link http://www.php.net/manual/ru/mongocollection.distinct.php
  413. * @param string $key The key to use.
  414. * @param array $query An optional query parameters
  415. * @return array|bool Returns an array of distinct values, or FALSE on failure
  416. */
  417. public function distinct($key, array $query = [])
  418. {
  419. try {
  420. return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, TypeConverter::fromLegacy($query)));
  421. } catch (\MongoDB\Driver\Exception\Exception $e) {
  422. return false;
  423. }
  424. }
  425. /**
  426. * Update a document and return it
  427. *
  428. * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
  429. * @param array $query The query criteria to search for.
  430. * @param array $update The update criteria.
  431. * @param array $fields Optionally only return these fields.
  432. * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
  433. * @return array Returns the original document, or the modified document when new is set.
  434. */
  435. public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
  436. {
  437. $query = TypeConverter::fromLegacy($query);
  438. try {
  439. if (isset($options['remove'])) {
  440. unset($options['remove']);
  441. $document = $this->collection->findOneAndDelete($query, $options);
  442. } else {
  443. $update = is_array($update) ? $update : [];
  444. if (isset($options['update']) && is_array($options['update'])) {
  445. $update = $options['update'];
  446. unset($options['update']);
  447. }
  448. $update = TypeConverter::fromLegacy($update);
  449. if (isset($options['new'])) {
  450. $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
  451. unset($options['new']);
  452. }
  453. $options['projection'] = TypeConverter::convertProjection($fields);
  454. if (! \MongoDB\is_first_key_operator($update)) {
  455. $document = $this->collection->findOneAndReplace($query, $update, $options);
  456. } else {
  457. $document = $this->collection->findOneAndUpdate($query, $update, $options);
  458. }
  459. }
  460. } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
  461. throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
  462. } catch (\MongoDB\Driver\Exception\Exception $e) {
  463. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  464. }
  465. if ($document) {
  466. $document = TypeConverter::toLegacy($document);
  467. }
  468. return $document;
  469. }
  470. /**
  471. * Querys this collection, returning a single element
  472. *
  473. * @link http://www.php.net/manual/en/mongocollection.findone.php
  474. * @param array $query The fields for which to search.
  475. * @param array $fields Fields of the results to return.
  476. * @param array $options
  477. * @return array|null
  478. */
  479. public function findOne($query = [], array $fields = [], array $options = [])
  480. {
  481. // Can't typehint for array since MongoGridFS extends and accepts strings
  482. if (! is_array($query)) {
  483. trigger_error(sprintf('MongoCollection::findOne(): expects parameter 1 to be an array or object, %s given', gettype($query)), E_USER_WARNING);
  484. return;
  485. }
  486. $options = ['projection' => TypeConverter::convertProjection($fields)] + $options;
  487. try {
  488. $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
  489. } catch (\MongoDB\Driver\Exception\Exception $e) {
  490. throw ExceptionConverter::toLegacy($e);
  491. }
  492. if ($document !== null) {
  493. $document = TypeConverter::toLegacy($document);
  494. }
  495. return $document;
  496. }
  497. /**
  498. * Creates an index on the given field(s), or does nothing if the index already exists
  499. *
  500. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  501. * @param array $keys Field or fields to use as index.
  502. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  503. * @return array Returns the database response.
  504. */
  505. public function createIndex($keys, array $options = [])
  506. {
  507. if (is_string($keys)) {
  508. if (empty($keys)) {
  509. throw new MongoException('empty string passed as key field');
  510. }
  511. $keys = [$keys => 1];
  512. }
  513. if (is_object($keys)) {
  514. $keys = (array) $keys;
  515. }
  516. if (! is_array($keys) || ! count($keys)) {
  517. throw new MongoException('index specification has no elements');
  518. }
  519. if (! isset($options['name'])) {
  520. $options['name'] = \MongoDB\generate_index_name($keys);
  521. }
  522. $indexes = iterator_to_array($this->collection->listIndexes());
  523. $indexCount = count($indexes);
  524. $collectionExists = true;
  525. $indexExists = false;
  526. // listIndexes returns 0 for non-existing collections while the legacy driver returns 1
  527. if ($indexCount === 0) {
  528. $collectionExists = false;
  529. $indexCount = 1;
  530. }
  531. foreach ($indexes as $index) {
  532. if ($index->getKey() === $keys || $index->getName() === $options['name']) {
  533. $indexExists = true;
  534. break;
  535. }
  536. }
  537. try {
  538. foreach (['w', 'wTimeoutMS', 'safe', 'timeout', 'wtimeout'] as $invalidOption) {
  539. if (isset($options[$invalidOption])) {
  540. unset($options[$invalidOption]);
  541. }
  542. }
  543. $this->collection->createIndex($keys, $options);
  544. } catch (\MongoDB\Driver\Exception\Exception $e) {
  545. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  546. }
  547. $result = [
  548. 'createdCollectionAutomatically' => !$collectionExists,
  549. 'numIndexesBefore' => $indexCount,
  550. 'numIndexesAfter' => $indexCount,
  551. 'note' => 'all indexes already exist',
  552. 'ok' => 1.0,
  553. ];
  554. if (! $indexExists) {
  555. $result['numIndexesAfter']++;
  556. unset($result['note']);
  557. }
  558. return $result;
  559. }
  560. /**
  561. * Creates an index on the given field(s), or does nothing if the index already exists
  562. *
  563. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  564. * @param array $keys Field or fields to use as index.
  565. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  566. * @return array Returns the database response.
  567. * @deprecated Use MongoCollection::createIndex() instead.
  568. */
  569. public function ensureIndex(array $keys, array $options = [])
  570. {
  571. return $this->createIndex($keys, $options);
  572. }
  573. /**
  574. * Deletes an index from this collection
  575. *
  576. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  577. * @param string|array $keys Field or fields from which to delete the index.
  578. * @return array Returns the database response.
  579. */
  580. public function deleteIndex($keys)
  581. {
  582. if (is_string($keys)) {
  583. $indexName = $keys;
  584. if (! preg_match('#_-?1$#', $indexName)) {
  585. $indexName .= '_1';
  586. }
  587. } elseif (is_array($keys)) {
  588. $indexName = \MongoDB\generate_index_name($keys);
  589. } else {
  590. throw new \InvalidArgumentException();
  591. }
  592. try {
  593. return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
  594. } catch (\MongoDB\Driver\Exception\Exception $e) {
  595. return ExceptionConverter::toResultArray($e) + ['nIndexesWas' => count($this->getIndexInfo())];
  596. }
  597. }
  598. /**
  599. * Delete all indexes for this collection
  600. *
  601. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  602. * @return array Returns the database response.
  603. */
  604. public function deleteIndexes()
  605. {
  606. try {
  607. return TypeConverter::toLegacy($this->collection->dropIndexes());
  608. } catch (\MongoDB\Driver\Exception\Exception $e) {
  609. return ExceptionConverter::toResultArray($e);
  610. }
  611. }
  612. /**
  613. * Returns an array of index names for this collection
  614. *
  615. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  616. * @return array Returns a list of index names.
  617. */
  618. public function getIndexInfo()
  619. {
  620. $convertIndex = function (\MongoDB\Model\IndexInfo $indexInfo) {
  621. $infos = [
  622. 'v' => $indexInfo->getVersion(),
  623. 'key' => $indexInfo->getKey(),
  624. 'name' => $indexInfo->getName(),
  625. 'ns' => $indexInfo->getNamespace(),
  626. ];
  627. $additionalKeys = [
  628. 'unique',
  629. 'sparse',
  630. 'partialFilterExpression',
  631. 'expireAfterSeconds',
  632. 'storageEngine',
  633. 'weights',
  634. 'default_language',
  635. 'language_override',
  636. 'textIndexVersion',
  637. 'collation',
  638. '2dsphereIndexVersion',
  639. 'bucketSize'
  640. ];
  641. foreach ($additionalKeys as $key) {
  642. if (! isset($indexInfo[$key])) {
  643. continue;
  644. }
  645. $infos[$key] = $indexInfo[$key];
  646. }
  647. return $infos;
  648. };
  649. return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
  650. }
  651. /**
  652. * Counts the number of documents in this collection
  653. *
  654. * @link http://www.php.net/manual/en/mongocollection.count.php
  655. * @param array|stdClass $query
  656. * @param array $options
  657. * @return int Returns the number of documents matching the query.
  658. */
  659. public function count($query = [], $options = [])
  660. {
  661. try {
  662. // Handle legacy mode - limit and skip as second and third parameters, respectively
  663. if (! is_array($options)) {
  664. $limit = $options;
  665. $options = [];
  666. if ($limit !== null) {
  667. $options['limit'] = (int) $limit;
  668. }
  669. if (func_num_args() > 2) {
  670. $options['skip'] = (int) func_get_args()[2];
  671. }
  672. }
  673. return $this->collection->count(TypeConverter::fromLegacy($query), $options);
  674. } catch (\MongoDB\Driver\Exception\Exception $e) {
  675. throw ExceptionConverter::toLegacy($e);
  676. }
  677. }
  678. /**
  679. * Saves an object to this collection
  680. *
  681. * @link http://www.php.net/manual/en/mongocollection.save.php
  682. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  683. * @param array $options Options for the save.
  684. * @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.
  685. * @throws MongoCursorException if the "w" option is set and the write fails.
  686. * @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.
  687. * @return array|boolean If w was set, returns an array containing the status of the save.
  688. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  689. */
  690. public function save(&$a, array $options = [])
  691. {
  692. $id = $this->ensureDocumentHasMongoId($a);
  693. $document = (array) $a;
  694. $options['upsert'] = true;
  695. try {
  696. /** @var \MongoDB\UpdateResult $result */
  697. $result = $this->collection->replaceOne(
  698. TypeConverter::fromLegacy(['_id' => $id]),
  699. TypeConverter::fromLegacy($document),
  700. $this->convertWriteConcernOptions($options)
  701. );
  702. if (! $result->isAcknowledged()) {
  703. return true;
  704. }
  705. $resultArray = [
  706. 'ok' => 1.0,
  707. 'nModified' => $result->getModifiedCount(),
  708. 'n' => $result->getUpsertedCount() + $result->getModifiedCount(),
  709. 'err' => null,
  710. 'errmsg' => null,
  711. 'updatedExisting' => $result->getUpsertedCount() == 0,
  712. ];
  713. if ($result->getUpsertedId() !== null) {
  714. $resultArray['upserted'] = TypeConverter::toLegacy($result->getUpsertedId());
  715. }
  716. return $resultArray;
  717. } catch (\MongoDB\Driver\Exception\Exception $e) {
  718. throw ExceptionConverter::toLegacy($e);
  719. }
  720. }
  721. /**
  722. * Creates a database reference
  723. *
  724. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  725. * @param array|object $document_or_id Object to which to create a reference.
  726. * @return array Returns a database reference array.
  727. */
  728. public function createDBRef($document_or_id)
  729. {
  730. if ($document_or_id instanceof \MongoId) {
  731. $id = $document_or_id;
  732. } elseif (is_object($document_or_id)) {
  733. if (! isset($document_or_id->_id)) {
  734. return null;
  735. }
  736. $id = $document_or_id->_id;
  737. } elseif (is_array($document_or_id)) {
  738. if (! isset($document_or_id['_id'])) {
  739. return null;
  740. }
  741. $id = $document_or_id['_id'];
  742. } else {
  743. $id = $document_or_id;
  744. }
  745. return MongoDBRef::create($this->name, $id);
  746. }
  747. /**
  748. * Fetches the document pointed to by a database reference
  749. *
  750. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  751. * @param array $ref A database reference.
  752. * @return array Returns the database document pointed to by the reference.
  753. */
  754. public function getDBRef(array $ref)
  755. {
  756. return $this->db->getDBRef($ref);
  757. }
  758. /**
  759. * Performs an operation similar to SQL's GROUP BY command
  760. *
  761. * @link http://www.php.net/manual/en/mongocollection.group.php
  762. * @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.
  763. * @param array $initial Initial value of the aggregation counter object.
  764. * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
  765. * @param array $condition An condition that must be true for a row to be considered.
  766. * @return array
  767. */
  768. public function group($keys, array $initial, $reduce, array $condition = [])
  769. {
  770. if (is_string($reduce)) {
  771. $reduce = new MongoCode($reduce);
  772. }
  773. $command = [
  774. 'group' => [
  775. 'ns' => $this->name,
  776. '$reduce' => (string)$reduce,
  777. 'initial' => $initial,
  778. 'cond' => $condition,
  779. ],
  780. ];
  781. if ($keys instanceof MongoCode) {
  782. $command['group']['$keyf'] = (string)$keys;
  783. } else {
  784. $command['group']['key'] = $keys;
  785. }
  786. if (array_key_exists('condition', $condition)) {
  787. $command['group']['cond'] = $condition['condition'];
  788. }
  789. if (array_key_exists('finalize', $condition)) {
  790. if ($condition['finalize'] instanceof MongoCode) {
  791. $condition['finalize'] = (string)$condition['finalize'];
  792. }
  793. $command['group']['finalize'] = $condition['finalize'];
  794. }
  795. return $this->db->command($command);
  796. }
  797. /**
  798. * Returns an array of cursors to iterator over a full collection in parallel
  799. *
  800. * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
  801. * @param int $num_cursors The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.
  802. * @return MongoCommandCursor[]
  803. */
  804. public function parallelCollectionScan($num_cursors)
  805. {
  806. $this->notImplemented();
  807. }
  808. protected function notImplemented()
  809. {
  810. throw new \Exception('Not implemented');
  811. }
  812. /**
  813. * @return \MongoDB\Collection
  814. */
  815. private function createCollectionObject()
  816. {
  817. $options = [
  818. 'readPreference' => $this->readPreference,
  819. 'writeConcern' => $this->writeConcern,
  820. ];
  821. if ($this->collection === null) {
  822. $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
  823. } else {
  824. $this->collection = $this->collection->withOptions($options);
  825. }
  826. }
  827. /**
  828. * Converts legacy write concern options to a WriteConcern object
  829. *
  830. * @param array $options
  831. * @return array
  832. */
  833. private function convertWriteConcernOptions(array $options)
  834. {
  835. if (isset($options['safe'])) {
  836. $options['w'] = ($options['safe']) ? 1 : 0;
  837. }
  838. if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
  839. $options['wTimeoutMS'] = $options['wtimeout'];
  840. }
  841. if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
  842. $collectionWriteConcern = $this->getWriteConcern();
  843. $writeConcern = $this->createWriteConcernFromParameters(
  844. isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
  845. isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
  846. );
  847. $options['writeConcern'] = $writeConcern;
  848. }
  849. unset($options['safe']);
  850. unset($options['w']);
  851. unset($options['wTimeout']);
  852. unset($options['wTimeoutMS']);
  853. return $options;
  854. }
  855. /**
  856. * @param array|object $document
  857. * @return MongoId
  858. */
  859. private function ensureDocumentHasMongoId(&$document)
  860. {
  861. $checkKeys = function ($array) {
  862. foreach (array_keys($array) as $key) {
  863. if (empty($key) && $key !== 0) {
  864. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  865. }
  866. }
  867. };
  868. if (is_array($document)) {
  869. if (! isset($document['_id'])) {
  870. $document['_id'] = new \MongoId();
  871. }
  872. $checkKeys($document);
  873. return $document['_id'];
  874. } elseif (is_object($document)) {
  875. $reflectionObject = new \ReflectionObject($document);
  876. foreach ($reflectionObject->getProperties() as $property) {
  877. if (! $property->isPublic()) {
  878. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  879. }
  880. }
  881. if (! isset($document->_id)) {
  882. $document->_id = new \MongoId();
  883. }
  884. $checkKeys((array) $document);
  885. return $document->_id;
  886. }
  887. return null;
  888. }
  889. private function checkCollectionName($name)
  890. {
  891. if (empty($name)) {
  892. throw new Exception('Collection name cannot be empty');
  893. } elseif (strpos($name, chr(0)) !== false) {
  894. throw new Exception('Collection name cannot contain null bytes');
  895. }
  896. }
  897. /**
  898. * @return array
  899. */
  900. public function __sleep()
  901. {
  902. return ['db', 'name'];
  903. }
  904. }