MongoCollection.php 35 KB

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