MongoCollection.php 31 KB

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