MongoCollection.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. $this->mustBeArrayOrObject($a);
  248. try {
  249. $result = $this->collection->insertOne(
  250. TypeConverter::fromLegacy($a),
  251. $this->convertWriteConcernOptions($options)
  252. );
  253. } catch (\MongoDB\Driver\Exception\Exception $e) {
  254. throw ExceptionConverter::toLegacy($e);
  255. }
  256. if (! $result->isAcknowledged()) {
  257. return true;
  258. }
  259. return [
  260. 'ok' => 1.0,
  261. 'n' => 0,
  262. 'err' => null,
  263. 'errmsg' => null,
  264. ];
  265. }
  266. /**
  267. * Inserts multiple documents into this collection
  268. *
  269. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  270. * @param array $a An array of arrays.
  271. * @param array $options Options for the inserts.
  272. * @throws MongoCursorException
  273. * @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.
  274. */
  275. public function batchInsert(array &$a, array $options = [])
  276. {
  277. if (empty($a)) {
  278. throw new \MongoException('No write ops were included in the batch');
  279. }
  280. $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
  281. foreach ($a as $key => $item) {
  282. try {
  283. if (! $this->ensureDocumentHasMongoId($a[$key])) {
  284. if ($continueOnError) {
  285. unset($a[$key]);
  286. } else {
  287. trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  288. return;
  289. }
  290. }
  291. } catch (MongoException $e) {
  292. if (! $continueOnError) {
  293. throw $e;
  294. }
  295. }
  296. }
  297. try {
  298. $result = $this->collection->insertMany(
  299. TypeConverter::fromLegacy(array_values($a)),
  300. $this->convertWriteConcernOptions($options)
  301. );
  302. } catch (\MongoDB\Driver\Exception\Exception $e) {
  303. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  304. }
  305. if (! $result->isAcknowledged()) {
  306. return true;
  307. }
  308. return [
  309. 'ok' => 1.0,
  310. 'connectionId' => 0,
  311. 'n' => 0,
  312. 'syncMillis' => 0,
  313. 'writtenTo' => null,
  314. 'err' => null,
  315. ];
  316. }
  317. /**
  318. * Update records based on a given criteria
  319. *
  320. * @link http://www.php.net/manual/en/mongocollection.update.php
  321. * @param array|object $criteria Description of the objects to update.
  322. * @param array|object $newobj The object with which to update the matching records.
  323. * @param array $options
  324. * @return bool|array
  325. * @throws MongoException
  326. * @throws MongoWriteConcernException
  327. */
  328. public function update($criteria, $newobj, array $options = [])
  329. {
  330. $this->mustBeArrayOrObject($criteria);
  331. $this->mustBeArrayOrObject($newobj);
  332. $this->checkKeys((array) $newobj);
  333. $multiple = isset($options['multiple']) ? $options['multiple'] : false;
  334. $isReplace = ! \MongoDB\is_first_key_operator($newobj);
  335. if ($isReplace && $multiple) {
  336. throw new \MongoWriteConcernException('multi update only works with $ operators', 9);
  337. }
  338. unset($options['multiple']);
  339. $method = $isReplace ? 'replace' : 'update';
  340. $method .= $multiple ? 'Many' : 'One';
  341. try {
  342. /** @var \MongoDB\UpdateResult $result */
  343. $result = $this->collection->$method(
  344. TypeConverter::fromLegacy($criteria),
  345. TypeConverter::fromLegacy($newobj),
  346. $this->convertWriteConcernOptions($options)
  347. );
  348. } catch (\MongoDB\Driver\Exception\Exception $e) {
  349. throw ExceptionConverter::toLegacy($e);
  350. }
  351. if (! $result->isAcknowledged()) {
  352. return true;
  353. }
  354. return [
  355. 'ok' => 1.0,
  356. 'nModified' => $result->getModifiedCount(),
  357. 'n' => $result->getMatchedCount(),
  358. 'err' => null,
  359. 'errmsg' => null,
  360. 'updatedExisting' => $result->getUpsertedCount() == 0 && $result->getModifiedCount() > 0,
  361. ];
  362. }
  363. /**
  364. * Remove records from this collection
  365. *
  366. * @link http://www.php.net/manual/en/mongocollection.remove.php
  367. * @param array $criteria Query criteria for the documents to delete.
  368. * @param array $options An array of options for the remove operation.
  369. * @throws MongoCursorException
  370. * @throws MongoCursorTimeoutException
  371. * @return bool|array Returns an array containing the status of the removal
  372. * if the "w" option is set. Otherwise, returns TRUE.
  373. */
  374. public function remove(array $criteria = [], array $options = [])
  375. {
  376. $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
  377. $method = $multiple ? 'deleteMany' : 'deleteOne';
  378. try {
  379. /** @var \MongoDB\DeleteResult $result */
  380. $result = $this->collection->$method(
  381. TypeConverter::fromLegacy($criteria),
  382. $this->convertWriteConcernOptions($options)
  383. );
  384. } catch (\MongoDB\Driver\Exception\Exception $e) {
  385. throw ExceptionConverter::toLegacy($e);
  386. }
  387. if (! $result->isAcknowledged()) {
  388. return true;
  389. }
  390. return [
  391. 'ok' => 1.0,
  392. 'n' => $result->getDeletedCount(),
  393. 'err' => null,
  394. 'errmsg' => null
  395. ];
  396. }
  397. /**
  398. * Querys this collection
  399. *
  400. * @link http://www.php.net/manual/en/mongocollection.find.php
  401. * @param array $query The fields for which to search.
  402. * @param array $fields Fields of the results to return.
  403. * @return MongoCursor
  404. */
  405. public function find(array $query = [], array $fields = [])
  406. {
  407. $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
  408. $cursor->setReadPreference($this->getReadPreference());
  409. return $cursor;
  410. }
  411. /**
  412. * Retrieve a list of distinct values for the given key across a collection
  413. *
  414. * @link http://www.php.net/manual/ru/mongocollection.distinct.php
  415. * @param string $key The key to use.
  416. * @param array $query An optional query parameters
  417. * @return array|bool Returns an array of distinct values, or FALSE on failure
  418. */
  419. public function distinct($key, array $query = [])
  420. {
  421. try {
  422. return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, TypeConverter::fromLegacy($query)));
  423. } catch (\MongoDB\Driver\Exception\Exception $e) {
  424. return false;
  425. }
  426. }
  427. /**
  428. * Update a document and return it
  429. *
  430. * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
  431. * @param array $query The query criteria to search for.
  432. * @param array $update The update criteria.
  433. * @param array $fields Optionally only return these fields.
  434. * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
  435. * @return array Returns the original document, or the modified document when new is set.
  436. */
  437. public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
  438. {
  439. $query = TypeConverter::fromLegacy($query);
  440. try {
  441. if (isset($options['remove'])) {
  442. unset($options['remove']);
  443. $document = $this->collection->findOneAndDelete($query, $options);
  444. } else {
  445. $update = is_array($update) ? $update : [];
  446. if (isset($options['update']) && is_array($options['update'])) {
  447. $update = $options['update'];
  448. unset($options['update']);
  449. }
  450. $update = TypeConverter::fromLegacy($update);
  451. if (isset($options['new'])) {
  452. $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
  453. unset($options['new']);
  454. }
  455. $options['projection'] = TypeConverter::convertProjection($fields);
  456. if (! \MongoDB\is_first_key_operator($update)) {
  457. $document = $this->collection->findOneAndReplace($query, $update, $options);
  458. } else {
  459. $document = $this->collection->findOneAndUpdate($query, $update, $options);
  460. }
  461. }
  462. } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
  463. throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
  464. } catch (\MongoDB\Driver\Exception\Exception $e) {
  465. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  466. }
  467. if ($document) {
  468. $document = TypeConverter::toLegacy($document);
  469. }
  470. return $document;
  471. }
  472. /**
  473. * Querys this collection, returning a single element
  474. *
  475. * @link http://www.php.net/manual/en/mongocollection.findone.php
  476. * @param array $query The fields for which to search.
  477. * @param array $fields Fields of the results to return.
  478. * @param array $options
  479. * @return array|null
  480. */
  481. public function findOne($query = [], array $fields = [], array $options = [])
  482. {
  483. // Can't typehint for array since MongoGridFS extends and accepts strings
  484. if (! is_array($query)) {
  485. trigger_error(sprintf('MongoCollection::findOne(): expects parameter 1 to be an array or object, %s given', gettype($query)), E_USER_WARNING);
  486. return;
  487. }
  488. $options = ['projection' => TypeConverter::convertProjection($fields)] + $options;
  489. try {
  490. $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
  491. } catch (\MongoDB\Driver\Exception\Exception $e) {
  492. throw ExceptionConverter::toLegacy($e);
  493. }
  494. if ($document !== null) {
  495. $document = TypeConverter::toLegacy($document);
  496. }
  497. return $document;
  498. }
  499. /**
  500. * Creates an index on the given field(s), or does nothing if the index already exists
  501. *
  502. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  503. * @param array $keys Field or fields to use as index.
  504. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  505. * @return array Returns the database response.
  506. */
  507. public function createIndex($keys, array $options = [])
  508. {
  509. if (is_string($keys)) {
  510. if (empty($keys)) {
  511. throw new MongoException('empty string passed as key field');
  512. }
  513. $keys = [$keys => 1];
  514. }
  515. if (is_object($keys)) {
  516. $keys = (array) $keys;
  517. }
  518. if (! is_array($keys) || ! count($keys)) {
  519. throw new MongoException('index specification has no elements');
  520. }
  521. if (! isset($options['name'])) {
  522. $options['name'] = \MongoDB\generate_index_name($keys);
  523. }
  524. $indexes = iterator_to_array($this->collection->listIndexes());
  525. $indexCount = count($indexes);
  526. $collectionExists = true;
  527. $indexExists = false;
  528. // listIndexes returns 0 for non-existing collections while the legacy driver returns 1
  529. if ($indexCount === 0) {
  530. $collectionExists = false;
  531. $indexCount = 1;
  532. }
  533. foreach ($indexes as $index) {
  534. if ($index->getKey() === $keys || $index->getName() === $options['name']) {
  535. $indexExists = true;
  536. break;
  537. }
  538. }
  539. try {
  540. foreach (['w', 'wTimeoutMS', 'safe', 'timeout', 'wtimeout'] as $invalidOption) {
  541. if (isset($options[$invalidOption])) {
  542. unset($options[$invalidOption]);
  543. }
  544. }
  545. $this->collection->createIndex($keys, $options);
  546. } catch (\MongoDB\Driver\Exception\Exception $e) {
  547. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  548. }
  549. $result = [
  550. 'createdCollectionAutomatically' => !$collectionExists,
  551. 'numIndexesBefore' => $indexCount,
  552. 'numIndexesAfter' => $indexCount,
  553. 'note' => 'all indexes already exist',
  554. 'ok' => 1.0,
  555. ];
  556. if (! $indexExists) {
  557. $result['numIndexesAfter']++;
  558. unset($result['note']);
  559. }
  560. return $result;
  561. }
  562. /**
  563. * Creates an index on the given field(s), or does nothing if the index already exists
  564. *
  565. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  566. * @param array $keys Field or fields to use as index.
  567. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  568. * @return array Returns the database response.
  569. * @deprecated Use MongoCollection::createIndex() instead.
  570. */
  571. public function ensureIndex(array $keys, array $options = [])
  572. {
  573. return $this->createIndex($keys, $options);
  574. }
  575. /**
  576. * Deletes an index from this collection
  577. *
  578. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  579. * @param string|array $keys Field or fields from which to delete the index.
  580. * @return array Returns the database response.
  581. */
  582. public function deleteIndex($keys)
  583. {
  584. if (is_string($keys)) {
  585. $indexName = $keys;
  586. if (! preg_match('#_-?1$#', $indexName)) {
  587. $indexName .= '_1';
  588. }
  589. } elseif (is_array($keys)) {
  590. $indexName = \MongoDB\generate_index_name($keys);
  591. } else {
  592. throw new \InvalidArgumentException();
  593. }
  594. try {
  595. return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
  596. } catch (\MongoDB\Driver\Exception\Exception $e) {
  597. return ExceptionConverter::toResultArray($e) + ['nIndexesWas' => count($this->getIndexInfo())];
  598. }
  599. }
  600. /**
  601. * Delete all indexes for this collection
  602. *
  603. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  604. * @return array Returns the database response.
  605. */
  606. public function deleteIndexes()
  607. {
  608. try {
  609. return TypeConverter::toLegacy($this->collection->dropIndexes());
  610. } catch (\MongoDB\Driver\Exception\Exception $e) {
  611. return ExceptionConverter::toResultArray($e);
  612. }
  613. }
  614. /**
  615. * Returns an array of index names for this collection
  616. *
  617. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  618. * @return array Returns a list of index names.
  619. */
  620. public function getIndexInfo()
  621. {
  622. $convertIndex = function (\MongoDB\Model\IndexInfo $indexInfo) {
  623. $infos = [
  624. 'v' => $indexInfo->getVersion(),
  625. 'key' => $indexInfo->getKey(),
  626. 'name' => $indexInfo->getName(),
  627. 'ns' => $indexInfo->getNamespace(),
  628. ];
  629. $additionalKeys = [
  630. 'unique',
  631. 'sparse',
  632. 'partialFilterExpression',
  633. 'expireAfterSeconds',
  634. 'storageEngine',
  635. 'weights',
  636. 'default_language',
  637. 'language_override',
  638. 'textIndexVersion',
  639. 'collation',
  640. '2dsphereIndexVersion',
  641. 'bucketSize'
  642. ];
  643. foreach ($additionalKeys as $key) {
  644. if (! isset($indexInfo[$key])) {
  645. continue;
  646. }
  647. $infos[$key] = $indexInfo[$key];
  648. }
  649. return $infos;
  650. };
  651. return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
  652. }
  653. /**
  654. * Counts the number of documents in this collection
  655. *
  656. * @link http://www.php.net/manual/en/mongocollection.count.php
  657. * @param array|stdClass $query
  658. * @param array $options
  659. * @return int Returns the number of documents matching the query.
  660. */
  661. public function count($query = [], $options = [])
  662. {
  663. try {
  664. // Handle legacy mode - limit and skip as second and third parameters, respectively
  665. if (! is_array($options)) {
  666. $limit = $options;
  667. $options = [];
  668. if ($limit !== null) {
  669. $options['limit'] = (int) $limit;
  670. }
  671. if (func_num_args() > 2) {
  672. $options['skip'] = (int) func_get_args()[2];
  673. }
  674. }
  675. return $this->collection->count(TypeConverter::fromLegacy($query), $options);
  676. } catch (\MongoDB\Driver\Exception\Exception $e) {
  677. throw ExceptionConverter::toLegacy($e);
  678. }
  679. }
  680. /**
  681. * Saves an object to this collection
  682. *
  683. * @link http://www.php.net/manual/en/mongocollection.save.php
  684. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  685. * @param array $options Options for the save.
  686. * @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.
  687. * @throws MongoCursorException if the "w" option is set and the write fails.
  688. * @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.
  689. * @return array|boolean If w was set, returns an array containing the status of the save.
  690. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  691. */
  692. public function save(&$a, array $options = [])
  693. {
  694. $id = $this->ensureDocumentHasMongoId($a);
  695. $document = (array) $a;
  696. $options['upsert'] = true;
  697. try {
  698. /** @var \MongoDB\UpdateResult $result */
  699. $result = $this->collection->replaceOne(
  700. TypeConverter::fromLegacy(['_id' => $id]),
  701. TypeConverter::fromLegacy($document),
  702. $this->convertWriteConcernOptions($options)
  703. );
  704. if (! $result->isAcknowledged()) {
  705. return true;
  706. }
  707. $resultArray = [
  708. 'ok' => 1.0,
  709. 'nModified' => $result->getModifiedCount(),
  710. 'n' => $result->getUpsertedCount() + $result->getModifiedCount(),
  711. 'err' => null,
  712. 'errmsg' => null,
  713. 'updatedExisting' => $result->getUpsertedCount() == 0 && $result->getModifiedCount() > 0,
  714. ];
  715. if ($result->getUpsertedId() !== null) {
  716. $resultArray['upserted'] = TypeConverter::toLegacy($result->getUpsertedId());
  717. }
  718. return $resultArray;
  719. } catch (\MongoDB\Driver\Exception\Exception $e) {
  720. throw ExceptionConverter::toLegacy($e);
  721. }
  722. }
  723. /**
  724. * Creates a database reference
  725. *
  726. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  727. * @param array|object $document_or_id Object to which to create a reference.
  728. * @return array Returns a database reference array.
  729. */
  730. public function createDBRef($document_or_id)
  731. {
  732. if ($document_or_id instanceof \MongoId) {
  733. $id = $document_or_id;
  734. } elseif (is_object($document_or_id)) {
  735. if (! isset($document_or_id->_id)) {
  736. return null;
  737. }
  738. $id = $document_or_id->_id;
  739. } elseif (is_array($document_or_id)) {
  740. if (! isset($document_or_id['_id'])) {
  741. return null;
  742. }
  743. $id = $document_or_id['_id'];
  744. } else {
  745. $id = $document_or_id;
  746. }
  747. return MongoDBRef::create($this->name, $id);
  748. }
  749. /**
  750. * Fetches the document pointed to by a database reference
  751. *
  752. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  753. * @param array $ref A database reference.
  754. * @return array Returns the database document pointed to by the reference.
  755. */
  756. public function getDBRef(array $ref)
  757. {
  758. return $this->db->getDBRef($ref);
  759. }
  760. /**
  761. * Performs an operation similar to SQL's GROUP BY command
  762. *
  763. * @link http://www.php.net/manual/en/mongocollection.group.php
  764. * @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.
  765. * @param array $initial Initial value of the aggregation counter object.
  766. * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
  767. * @param array $condition An condition that must be true for a row to be considered.
  768. * @return array
  769. */
  770. public function group($keys, array $initial, $reduce, array $condition = [])
  771. {
  772. if (is_string($reduce)) {
  773. $reduce = new MongoCode($reduce);
  774. }
  775. $command = [
  776. 'group' => [
  777. 'ns' => $this->name,
  778. '$reduce' => (string) $reduce,
  779. 'initial' => $initial,
  780. 'cond' => $condition,
  781. ],
  782. ];
  783. if ($keys instanceof MongoCode) {
  784. $command['group']['$keyf'] = (string) $keys;
  785. } else {
  786. $command['group']['key'] = $keys;
  787. }
  788. if (array_key_exists('condition', $condition)) {
  789. $command['group']['cond'] = $condition['condition'];
  790. }
  791. if (array_key_exists('finalize', $condition)) {
  792. if ($condition['finalize'] instanceof MongoCode) {
  793. $condition['finalize'] = (string) $condition['finalize'];
  794. }
  795. $command['group']['finalize'] = $condition['finalize'];
  796. }
  797. return $this->db->command($command);
  798. }
  799. /**
  800. * Returns an array of cursors to iterator over a full collection in parallel
  801. *
  802. * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
  803. * @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.
  804. * @return MongoCommandCursor[]
  805. */
  806. public function parallelCollectionScan($num_cursors)
  807. {
  808. $this->notImplemented();
  809. }
  810. protected function notImplemented()
  811. {
  812. throw new \Exception('Not implemented');
  813. }
  814. /**
  815. * @return \MongoDB\Collection
  816. */
  817. private function createCollectionObject()
  818. {
  819. $options = [
  820. 'readPreference' => $this->readPreference,
  821. 'writeConcern' => $this->writeConcern,
  822. ];
  823. if ($this->collection === null) {
  824. $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
  825. } else {
  826. $this->collection = $this->collection->withOptions($options);
  827. }
  828. }
  829. /**
  830. * Converts legacy write concern options to a WriteConcern object
  831. *
  832. * @param array $options
  833. * @return array
  834. */
  835. private function convertWriteConcernOptions(array $options)
  836. {
  837. if (isset($options['safe'])) {
  838. $options['w'] = ($options['safe']) ? 1 : 0;
  839. }
  840. if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
  841. $options['wTimeoutMS'] = $options['wtimeout'];
  842. }
  843. if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
  844. $collectionWriteConcern = $this->getWriteConcern();
  845. $writeConcern = $this->createWriteConcernFromParameters(
  846. isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
  847. isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
  848. );
  849. $options['writeConcern'] = $writeConcern;
  850. }
  851. unset($options['safe']);
  852. unset($options['w']);
  853. unset($options['wTimeout']);
  854. unset($options['wTimeoutMS']);
  855. return $options;
  856. }
  857. private function checkKeys(array $array)
  858. {
  859. foreach ($array as $key => $value) {
  860. if (empty($key) && $key !== 0) {
  861. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  862. }
  863. if (is_object($value) || is_array($value)) {
  864. $this->checkKeys((array) $value);
  865. }
  866. }
  867. }
  868. /**
  869. * @param array|object $document
  870. * @return MongoId
  871. */
  872. private function ensureDocumentHasMongoId(&$document)
  873. {
  874. if (is_array($document)) {
  875. if (! isset($document['_id'])) {
  876. $document['_id'] = new \MongoId();
  877. }
  878. $this->checkKeys($document);
  879. return $document['_id'];
  880. } elseif (is_object($document)) {
  881. $reflectionObject = new \ReflectionObject($document);
  882. foreach ($reflectionObject->getProperties() as $property) {
  883. if (! $property->isPublic()) {
  884. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  885. }
  886. }
  887. if (! isset($document->_id)) {
  888. $document->_id = new \MongoId();
  889. }
  890. $this->checkKeys((array) $document);
  891. return $document->_id;
  892. }
  893. return null;
  894. }
  895. private function checkCollectionName($name)
  896. {
  897. if (empty($name)) {
  898. throw new Exception('Collection name cannot be empty');
  899. } elseif (strpos($name, chr(0)) !== false) {
  900. throw new Exception('Collection name cannot contain null bytes');
  901. }
  902. }
  903. /**
  904. * @return array
  905. */
  906. public function __sleep()
  907. {
  908. return ['db', 'name'];
  909. }
  910. private function mustBeArrayOrObject($a)
  911. {
  912. if (!is_array($a) && !is_object($a)) {
  913. throw new \MongoException('document must be an array or object');
  914. }
  915. }
  916. }