MongoCollection.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. $command = [
  130. 'aggregate' => $this->name,
  131. 'pipeline' => $pipeline
  132. ];
  133. $command += $options;
  134. try {
  135. return $this->db->command($command);
  136. } catch (MongoCursorTimeoutException $e) {
  137. throw new MongoExecutionTimeoutException($e->getMessage(), $e->getCode(), $e);
  138. }
  139. }
  140. /**
  141. * Execute an aggregation pipeline command and retrieve results through a cursor
  142. *
  143. * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
  144. * @param array $pipeline
  145. * @param array $options
  146. * @return MongoCommandCursor
  147. */
  148. public function aggregateCursor(array $pipeline, array $options = [])
  149. {
  150. // Build command manually, can't use mongo-php-library here
  151. $command = [
  152. 'aggregate' => $this->name,
  153. 'pipeline' => $pipeline
  154. ];
  155. // Convert cursor option
  156. if (! isset($options['cursor'])) {
  157. $options['cursor'] = true;
  158. }
  159. $command += $options;
  160. $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
  161. $cursor->setReadPreference($this->getReadPreference());
  162. return $cursor;
  163. }
  164. /**
  165. * Returns this collection's name
  166. *
  167. * @link http://www.php.net/manual/en/mongocollection.getname.php
  168. * @return string
  169. */
  170. public function getName()
  171. {
  172. return $this->name;
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function setReadPreference($readPreference, $tags = null)
  178. {
  179. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  180. $this->createCollectionObject();
  181. return $result;
  182. }
  183. /**
  184. * {@inheritdoc}
  185. */
  186. public function setWriteConcern($wstring, $wtimeout = 0)
  187. {
  188. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  189. $this->createCollectionObject();
  190. return $result;
  191. }
  192. /**
  193. * Drops this collection
  194. *
  195. * @link http://www.php.net/manual/en/mongocollection.drop.php
  196. * @return array Returns the database response.
  197. */
  198. public function drop()
  199. {
  200. return TypeConverter::toLegacy($this->collection->drop());
  201. }
  202. /**
  203. * Validates this collection
  204. *
  205. * @link http://www.php.net/manual/en/mongocollection.validate.php
  206. * @param bool $scan_data Only validate indices, not the base collection.
  207. * @return array Returns the database's evaluation of this object.
  208. */
  209. public function validate($scan_data = FALSE)
  210. {
  211. $command = [
  212. 'validate' => $this->name,
  213. 'full' => $scan_data,
  214. ];
  215. return $this->db->command($command);
  216. }
  217. /**
  218. * Inserts an array into the collection
  219. *
  220. * @link http://www.php.net/manual/en/mongocollection.insert.php
  221. * @param array|object $a
  222. * @param array $options
  223. * @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.
  224. * @throws MongoCursorException if the "w" option is set and the write fails.
  225. * @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.
  226. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
  227. */
  228. public function insert(&$a, array $options = [])
  229. {
  230. if (! $this->ensureDocumentHasMongoId($a)) {
  231. trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  232. return;
  233. }
  234. if (! count((array)$a)) {
  235. throw new \MongoException('document must be an array or object');
  236. }
  237. try {
  238. $result = $this->collection->insertOne(
  239. TypeConverter::fromLegacy($a),
  240. $this->convertWriteConcernOptions($options)
  241. );
  242. } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
  243. $writeResult = $e->getWriteResult();
  244. $writeError = $writeResult->getWriteErrors()[0];
  245. return [
  246. 'ok' => 0.0,
  247. 'n' => 0,
  248. 'err' => $writeError->getCode(),
  249. 'errmsg' => $writeError->getMessage(),
  250. ];
  251. } catch (\MongoDB\Driver\Exception\Exception $e) {
  252. throw ExceptionConverter::toLegacy($e);
  253. }
  254. if (! $result->isAcknowledged()) {
  255. return true;
  256. }
  257. return [
  258. 'ok' => 1.0,
  259. 'n' => 0,
  260. 'err' => null,
  261. 'errmsg' => null,
  262. ];
  263. }
  264. /**
  265. * Inserts multiple documents into this collection
  266. *
  267. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  268. * @param array $a An array of arrays.
  269. * @param array $options Options for the inserts.
  270. * @throws MongoCursorException
  271. * @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.
  272. */
  273. public function batchInsert(array &$a, array $options = [])
  274. {
  275. if (empty($a)) {
  276. throw new \MongoException('No write ops were included in the batch');
  277. }
  278. $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
  279. foreach ($a as $key => $item) {
  280. try {
  281. if (! $this->ensureDocumentHasMongoId($a[$key])) {
  282. if ($continueOnError) {
  283. unset($a[$key]);
  284. } else {
  285. trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  286. return;
  287. }
  288. }
  289. } catch (MongoException $e) {
  290. if ( ! $continueOnError) {
  291. throw $e;
  292. }
  293. }
  294. }
  295. try {
  296. $result = $this->collection->insertMany(
  297. TypeConverter::fromLegacy(array_values($a)),
  298. $this->convertWriteConcernOptions($options)
  299. );
  300. } catch (\MongoDB\Driver\Exception\Exception $e) {
  301. throw ExceptionConverter::toLegacy($e);
  302. }
  303. if (! $result->isAcknowledged()) {
  304. return true;
  305. }
  306. return [
  307. 'connectionId' => 0,
  308. 'n' => 0,
  309. 'syncMillis' => 0,
  310. 'writtenTo' => null,
  311. 'err' => null,
  312. 'errmsg' => null,
  313. ];
  314. }
  315. /**
  316. * Update records based on a given criteria
  317. *
  318. * @link http://www.php.net/manual/en/mongocollection.update.php
  319. * @param array $criteria Description of the objects to update.
  320. * @param array $newobj The object with which to update the matching records.
  321. * @param array $options
  322. * @throws MongoCursorException
  323. * @return boolean
  324. */
  325. public function update(array $criteria , array $newobj, array $options = [])
  326. {
  327. $multiple = isset($options['multiple']) ? $options['multiple'] : false;
  328. $method = $multiple ? 'updateMany' : 'updateOne';
  329. unset($options['multiple']);
  330. try {
  331. /** @var \MongoDB\UpdateResult $result */
  332. $result = $this->collection->$method(
  333. TypeConverter::fromLegacy($criteria),
  334. TypeConverter::fromLegacy($newobj),
  335. $this->convertWriteConcernOptions($options)
  336. );
  337. } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
  338. $writeResult = $e->getWriteResult();
  339. $writeError = $writeResult->getWriteErrors()[0];
  340. return [
  341. 'ok' => 0.0,
  342. 'nModified' => $writeResult->getModifiedCount(),
  343. 'n' => $writeResult->getMatchedCount(),
  344. 'err' => $writeError->getCode(),
  345. 'errmsg' => $writeError->getMessage(),
  346. 'updatedExisting' => $writeResult->getUpsertedCount() == 0,
  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,
  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, $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) ? TypeConverter::fromLegacy($update) : [];
  446. if (isset($options['new'])) {
  447. $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
  448. unset($options['new']);
  449. }
  450. $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
  451. $document = $this->collection->findOneAndUpdate($query, $update, $options);
  452. }
  453. } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
  454. throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
  455. } catch (\MongoDB\Driver\Exception\Exception $e) {
  456. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  457. }
  458. if ($document) {
  459. $document = TypeConverter::toLegacy($document);
  460. }
  461. return $document;
  462. }
  463. /**
  464. * Querys this collection, returning a single element
  465. *
  466. * @link http://www.php.net/manual/en/mongocollection.findone.php
  467. * @param array $query The fields for which to search.
  468. * @param array $fields Fields of the results to return.
  469. * @param array $options
  470. * @return array|null
  471. */
  472. public function findOne(array $query = [], array $fields = [], array $options = [])
  473. {
  474. $options = ['projection' => $fields] + $options;
  475. try {
  476. $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
  477. } catch (\MongoDB\Driver\Exception\Exception $e) {
  478. throw ExceptionConverter::toLegacy($e);
  479. }
  480. if ($document !== null) {
  481. $document = TypeConverter::toLegacy($document);
  482. }
  483. return $document;
  484. }
  485. /**
  486. * Creates an index on the given field(s), or does nothing if the index already exists
  487. *
  488. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  489. * @param array $keys Field or fields to use as index.
  490. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  491. * @return array Returns the database response.
  492. *
  493. * @todo This method does not yet return the correct result
  494. */
  495. public function createIndex($keys, array $options = [])
  496. {
  497. if (is_string($keys)) {
  498. if (empty($keys)) {
  499. throw new MongoException('empty string passed as key field');
  500. }
  501. $keys = [$keys => 1];
  502. }
  503. if (is_object($keys)) {
  504. $keys = (array) $keys;
  505. }
  506. if (! is_array($keys) || ! count($keys)) {
  507. throw new MongoException('keys cannot be empty');
  508. }
  509. // duplicate
  510. $neededOptions = ['unique' => 1, 'sparse' => 1, 'expireAfterSeconds' => 1, 'background' => 1, 'dropDups' => 1];
  511. $indexOptions = array_intersect_key($options, $neededOptions);
  512. $indexes = $this->collection->listIndexes();
  513. foreach ($indexes as $index) {
  514. if (! empty($options['name']) && $index->getName() === $options['name']) {
  515. throw new \MongoResultException(sprintf('index with name: %s already exists', $index->getName()));
  516. }
  517. if ($index->getKey() == $keys) {
  518. $currentIndexOptions = array_intersect_key($index->__debugInfo(), $neededOptions);
  519. unset($currentIndexOptions['name']);
  520. if ($currentIndexOptions != $indexOptions) {
  521. throw new \MongoResultException('Index with same keys but different options already exists');
  522. }
  523. return [
  524. 'createdCollectionAutomatically' => false,
  525. 'numIndexesBefore' => count($indexes),
  526. 'numIndexesAfter' => count($indexes),
  527. 'note' => 'all indexes already exist',
  528. 'ok' => 1.0
  529. ];
  530. }
  531. }
  532. try {
  533. $this->collection->createIndex($keys, $this->convertWriteConcernOptions($options));
  534. } catch (\MongoDB\Driver\Exception\Exception $e) {
  535. throw ExceptionConverter::toLegacy($e);
  536. }
  537. return [
  538. 'createdCollectionAutomatically' => true,
  539. 'numIndexesBefore' => count($indexes),
  540. 'numIndexesAfter' => count($indexes) + 1,
  541. 'ok' => 1.0
  542. ];
  543. }
  544. /**
  545. * Creates an index on the given field(s), or does nothing if the index already exists
  546. *
  547. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  548. * @param array $keys Field or fields to use as index.
  549. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  550. * @return boolean always true
  551. * @deprecated Use MongoCollection::createIndex() instead.
  552. */
  553. public function ensureIndex(array $keys, array $options = [])
  554. {
  555. $this->createIndex($keys, $options);
  556. return true;
  557. }
  558. /**
  559. * Deletes an index from this collection
  560. *
  561. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  562. * @param string|array $keys Field or fields from which to delete the index.
  563. * @return array Returns the database response.
  564. */
  565. public function deleteIndex($keys)
  566. {
  567. if (is_string($keys)) {
  568. $indexName = $keys;
  569. } elseif (is_array($keys)) {
  570. $indexName = \MongoDB\generate_index_name($keys);
  571. } else {
  572. throw new \InvalidArgumentException();
  573. }
  574. return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
  575. }
  576. /**
  577. * Delete all indexes for this collection
  578. *
  579. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  580. * @return array Returns the database response.
  581. */
  582. public function deleteIndexes()
  583. {
  584. return TypeConverter::toLegacy($this->collection->dropIndexes());
  585. }
  586. /**
  587. * Returns an array of index names for this collection
  588. *
  589. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  590. * @return array Returns a list of index names.
  591. */
  592. public function getIndexInfo()
  593. {
  594. $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
  595. return [
  596. 'v' => $indexInfo->getVersion(),
  597. 'key' => $indexInfo->getKey(),
  598. 'name' => $indexInfo->getName(),
  599. 'ns' => $indexInfo->getNamespace(),
  600. ];
  601. };
  602. return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
  603. }
  604. /**
  605. * Counts the number of documents in this collection
  606. *
  607. * @link http://www.php.net/manual/en/mongocollection.count.php
  608. * @param array|stdClass $query
  609. * @param array $options
  610. * @return int Returns the number of documents matching the query.
  611. */
  612. public function count($query = [], array $options = [])
  613. {
  614. try {
  615. return $this->collection->count(TypeConverter::fromLegacy($query), $options);
  616. } catch (\MongoDB\Driver\Exception\Exception $e) {
  617. throw ExceptionConverter::toLegacy($e);
  618. }
  619. }
  620. /**
  621. * Saves an object to this collection
  622. *
  623. * @link http://www.php.net/manual/en/mongocollection.save.php
  624. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  625. * @param array $options Options for the save.
  626. * @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.
  627. * @throws MongoCursorException if the "w" option is set and the write fails.
  628. * @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.
  629. * @return array|boolean If w was set, returns an array containing the status of the save.
  630. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  631. */
  632. public function save(&$a, array $options = [])
  633. {
  634. $id = $this->ensureDocumentHasMongoId($a);
  635. $document = (array) $a;
  636. $options['upsert'] = true;
  637. try {
  638. /** @var \MongoDB\UpdateResult $result */
  639. $result = $this->collection->replaceOne(
  640. TypeConverter::fromLegacy(['_id' => $id]),
  641. TypeConverter::fromLegacy($document),
  642. $this->convertWriteConcernOptions($options)
  643. );
  644. } catch (\MongoDB\Driver\Exception\Exception $e) {
  645. ExceptionConverter::toLegacy($e);
  646. }
  647. if (!$result->isAcknowledged()) {
  648. return true;
  649. }
  650. return [
  651. 'ok' => 1.0,
  652. 'nModified' => $result->getModifiedCount(),
  653. 'n' => $result->getMatchedCount(),
  654. 'err' => null,
  655. 'errmsg' => null,
  656. 'updatedExisting' => $result->getUpsertedCount() == 0,
  657. ];
  658. }
  659. /**
  660. * Creates a database reference
  661. *
  662. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  663. * @param array|object $document_or_id Object to which to create a reference.
  664. * @return array Returns a database reference array.
  665. */
  666. public function createDBRef($document_or_id)
  667. {
  668. if ($document_or_id instanceof \MongoId) {
  669. $id = $document_or_id;
  670. } elseif (is_object($document_or_id)) {
  671. if (! isset($document_or_id->_id)) {
  672. return null;
  673. }
  674. $id = $document_or_id->_id;
  675. } elseif (is_array($document_or_id)) {
  676. if (! isset($document_or_id['_id'])) {
  677. return null;
  678. }
  679. $id = $document_or_id['_id'];
  680. } else {
  681. $id = $document_or_id;
  682. }
  683. return MongoDBRef::create($this->name, $id);
  684. }
  685. /**
  686. * Fetches the document pointed to by a database reference
  687. *
  688. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  689. * @param array $ref A database reference.
  690. * @return array Returns the database document pointed to by the reference.
  691. */
  692. public function getDBRef(array $ref)
  693. {
  694. return $this->db->getDBRef($ref);
  695. }
  696. /**
  697. * Performs an operation similar to SQL's GROUP BY command
  698. *
  699. * @link http://www.php.net/manual/en/mongocollection.group.php
  700. * @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.
  701. * @param array $initial Initial value of the aggregation counter object.
  702. * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
  703. * @param array $condition An condition that must be true for a row to be considered.
  704. * @return array
  705. */
  706. public function group($keys, array $initial, $reduce, array $condition = [])
  707. {
  708. if (is_string($reduce)) {
  709. $reduce = new MongoCode($reduce);
  710. }
  711. $command = [
  712. 'group' => [
  713. 'ns' => $this->name,
  714. '$reduce' => (string)$reduce,
  715. 'initial' => $initial,
  716. 'cond' => $condition,
  717. ],
  718. ];
  719. if ($keys instanceof MongoCode) {
  720. $command['group']['$keyf'] = (string)$keys;
  721. } else {
  722. $command['group']['key'] = $keys;
  723. }
  724. if (array_key_exists('condition', $condition)) {
  725. $command['group']['cond'] = $condition['condition'];
  726. }
  727. if (array_key_exists('finalize', $condition)) {
  728. if ($condition['finalize'] instanceof MongoCode) {
  729. $condition['finalize'] = (string)$condition['finalize'];
  730. }
  731. $command['group']['finalize'] = $condition['finalize'];
  732. }
  733. return $this->db->command($command);
  734. }
  735. /**
  736. * Returns an array of cursors to iterator over a full collection in parallel
  737. *
  738. * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
  739. * @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.
  740. * @return MongoCommandCursor[]
  741. */
  742. public function parallelCollectionScan($num_cursors)
  743. {
  744. $this->notImplemented();
  745. }
  746. protected function notImplemented()
  747. {
  748. throw new \Exception('Not implemented');
  749. }
  750. /**
  751. * @return \MongoDB\Collection
  752. */
  753. private function createCollectionObject()
  754. {
  755. $options = [
  756. 'readPreference' => $this->readPreference,
  757. 'writeConcern' => $this->writeConcern,
  758. ];
  759. if ($this->collection === null) {
  760. $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
  761. } else {
  762. $this->collection = $this->collection->withOptions($options);
  763. }
  764. }
  765. /**
  766. * Converts legacy write concern options to a WriteConcern object
  767. *
  768. * @param array $options
  769. * @return array
  770. */
  771. private function convertWriteConcernOptions(array $options)
  772. {
  773. if (isset($options['safe'])) {
  774. $options['w'] = ($options['safe']) ? 1 : 0;
  775. }
  776. if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
  777. $options['wTimeoutMS'] = $options['wtimeout'];
  778. }
  779. if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
  780. $collectionWriteConcern = $this->getWriteConcern();
  781. $writeConcern = $this->createWriteConcernFromParameters(
  782. isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
  783. isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
  784. );
  785. $options['writeConcern'] = $writeConcern;
  786. }
  787. unset($options['safe']);
  788. unset($options['w']);
  789. unset($options['wTimeout']);
  790. unset($options['wTimeoutMS']);
  791. return $options;
  792. }
  793. /**
  794. * @param array|object $document
  795. * @return MongoId
  796. */
  797. private function ensureDocumentHasMongoId(&$document)
  798. {
  799. $checkKeys = function($array) {
  800. foreach (array_keys($array) as $key) {
  801. if (is_int($key) || empty($key) || strpos($key, '*') === 1) {
  802. throw new \MongoException('document contain invalid key');
  803. }
  804. }
  805. };
  806. if (is_array($document)) {
  807. if (empty($document)) {
  808. throw new \MongoException('document cannot be empty');
  809. }
  810. if (! isset($document['_id'])) {
  811. $document['_id'] = new \MongoId();
  812. }
  813. $checkKeys($document);
  814. return $document['_id'];
  815. } elseif (is_object($document)) {
  816. if (empty((array) $document)) {
  817. throw new \MongoException('document cannot be empty');
  818. }
  819. if (! isset($document->_id)) {
  820. $document->_id = new \MongoId();
  821. }
  822. $checkKeys((array) $document);
  823. return $document->_id;
  824. }
  825. return null;
  826. }
  827. private function checkCollectionName($name)
  828. {
  829. if (empty($name)) {
  830. throw new Exception('Collection name cannot be empty');
  831. } elseif (strpos($name, chr(0)) !== false) {
  832. throw new Exception('Collection name cannot contain null bytes');
  833. }
  834. }
  835. }