MongoCollection.php 31 KB

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