MongoCollection.php 31 KB

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