MongoCollection.php 25 KB

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