Collection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mongodb;
  8. use MongoDB\BSON\ObjectID;
  9. use yii\base\BaseObject;
  10. use Yii;
  11. /**
  12. * Collection represents the Mongo collection information.
  13. *
  14. * A collection object is usually created by calling [[Database::getCollection()]] or [[Connection::getCollection()]].
  15. *
  16. * Collection provides the basic interface for the Mongo queries, mostly: insert, update, delete operations.
  17. * For example:
  18. *
  19. * ```php
  20. * $collection = Yii::$app->mongodb->getCollection('customer');
  21. * $collection->insert(['name' => 'John Smith', 'status' => 1]);
  22. * ```
  23. *
  24. * Collection also provides shortcut for [[Command]] methods, such as [[group()]], [[mapReduce()]] and so on.
  25. *
  26. * To perform "find" queries, please use [[Query]] instead.
  27. *
  28. * @property string $fullName Full name of this collection, including database name. This property is
  29. * read-only.
  30. *
  31. * @author Paul Klimov <klimov.paul@gmail.com>
  32. * @since 2.0
  33. */
  34. class Collection extends BaseObject
  35. {
  36. /**
  37. * @var Database MongoDB database instance.
  38. */
  39. public $database;
  40. /**
  41. * @var string name of this collection.
  42. */
  43. public $name;
  44. /**
  45. * @return string full name of this collection, including database name.
  46. */
  47. public function getFullName()
  48. {
  49. return $this->database->name . '.' . $this->name;
  50. }
  51. /**
  52. * Drops this collection.
  53. * @throws Exception on failure.
  54. * @return bool whether the operation successful.
  55. */
  56. public function drop()
  57. {
  58. return $this->database->dropCollection($this->name);
  59. }
  60. /**
  61. * Returns the list of defined indexes.
  62. * @return array list of indexes info.
  63. * @param array $options list of options in format: optionName => optionValue.
  64. * @since 2.1
  65. */
  66. public function listIndexes($options = [])
  67. {
  68. return $this->database->createCommand()->listIndexes($this->name, $options);
  69. }
  70. /**
  71. * Creates several indexes at once.
  72. * Example:
  73. *
  74. * ```php
  75. * $collection = Yii::$app->mongo->getCollection('customer');
  76. * $collection->createIndexes([
  77. * [
  78. * 'key' => ['name'],
  79. * ],
  80. * [
  81. * 'key' => [
  82. * 'email' => 1,
  83. * 'address' => -1,
  84. * ],
  85. * 'name' => 'my_index'
  86. * ],
  87. * ]);
  88. * ```
  89. *
  90. * @param array $indexes indexes specification, each index should be specified as an array.
  91. * @param array[] $indexes indexes specification. Each specification should be an array in format: optionName => value
  92. * The main options are:
  93. *
  94. * - keys: array, column names with sort order, to be indexed. This option is mandatory.
  95. * - unique: bool, whether to create unique index.
  96. * - name: string, the name of the index, if not set it will be generated automatically.
  97. * - background: bool, whether to bind index in the background.
  98. * - sparse: bool, whether index should reference only documents with the specified field.
  99. *
  100. * See [[https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types]]
  101. * for the full list of options.
  102. * @return bool whether operation was successful.
  103. * @since 2.1
  104. */
  105. public function createIndexes($indexes)
  106. {
  107. return $this->database->createCommand()->createIndexes($this->name, $indexes);
  108. }
  109. /**
  110. * Drops collection indexes by name.
  111. * @param string $indexes wildcard for name of the indexes to be dropped.
  112. * You can use `*` to drop all indexes.
  113. * @return int count of dropped indexes.
  114. */
  115. public function dropIndexes($indexes)
  116. {
  117. $result = $this->database->createCommand()->dropIndexes($this->name, $indexes);
  118. return $result['nIndexesWas'];
  119. }
  120. /**
  121. * Creates an index on the collection and the specified fields.
  122. * @param array|string $columns column name or list of column names.
  123. * If array is given, each element in the array has as key the field name, and as
  124. * value either 1 for ascending sort, or -1 for descending sort.
  125. * You can specify field using native numeric key with the field name as a value,
  126. * in this case ascending sort will be used.
  127. * For example:
  128. *
  129. * ```php
  130. * [
  131. * 'name',
  132. * 'status' => -1,
  133. * ]
  134. * ```
  135. *
  136. * @param array $options list of options in format: optionName => optionValue.
  137. * @throws Exception on failure.
  138. * @return bool whether the operation successful.
  139. */
  140. public function createIndex($columns, $options = [])
  141. {
  142. $index = array_merge(['key' => $columns], $options);
  143. return $this->database->createCommand()->createIndexes($this->name, [$index]);
  144. }
  145. /**
  146. * Drop indexes for specified column(s).
  147. * @param string|array $columns column name or list of column names.
  148. * If array is given, each element in the array has as key the field name, and as
  149. * value either 1 for ascending sort, or -1 for descending sort.
  150. * Use value 'text' to specify text index.
  151. * You can specify field using native numeric key with the field name as a value,
  152. * in this case ascending sort will be used.
  153. * For example:
  154. *
  155. * ```php
  156. * [
  157. * 'name',
  158. * 'status' => -1,
  159. * 'description' => 'text',
  160. * ]
  161. * ```
  162. *
  163. * @throws Exception on failure.
  164. * @return bool whether the operation successful.
  165. */
  166. public function dropIndex($columns)
  167. {
  168. $existingIndexes = $this->listIndexes();
  169. $indexKey = $this->database->connection->getQueryBuilder()->buildSortFields($columns);
  170. foreach ($existingIndexes as $index) {
  171. if ($index['key'] == $indexKey) {
  172. $this->database->createCommand()->dropIndexes($this->name, $index['name']);
  173. return true;
  174. }
  175. }
  176. // Index plugin usage such as 'text' may cause unpredictable index 'key' structure, thus index name should be used
  177. $indexName = $this->database->connection->getQueryBuilder()->generateIndexName($indexKey);
  178. foreach ($existingIndexes as $index) {
  179. if ($index['name'] === $indexName) {
  180. $this->database->createCommand()->dropIndexes($this->name, $index['name']);
  181. return true;
  182. }
  183. }
  184. throw new Exception('Index to be dropped does not exist.');
  185. }
  186. /**
  187. * Drops all indexes for this collection.
  188. * @throws Exception on failure.
  189. * @return int count of dropped indexes.
  190. */
  191. public function dropAllIndexes()
  192. {
  193. $result = $this->database->createCommand()->dropIndexes($this->name, '*');
  194. return $result['nIndexesWas'];
  195. }
  196. /**
  197. * Returns a cursor for the search results.
  198. * In order to perform "find" queries use [[Query]] class.
  199. * @param array $condition query condition
  200. * @param array $fields fields to be selected
  201. * @param array $options query options (available since 2.1).
  202. * @return \MongoDB\Driver\Cursor cursor for the search results
  203. * @see Query
  204. */
  205. public function find($condition = [], $fields = [], $options = [])
  206. {
  207. if (!empty($fields)) {
  208. $options['projection'] = $fields;
  209. }
  210. return $this->database->createCommand()->find($this->name, $condition, $options);
  211. }
  212. /**
  213. * Returns a single document.
  214. * @param array $condition query condition
  215. * @param array $fields fields to be selected
  216. * @param array $options query options (available since 2.1).
  217. * @return array|null the single document. Null is returned if the query results in nothing.
  218. */
  219. public function findOne($condition = [], $fields = [], $options = [])
  220. {
  221. $options['limit'] = 1;
  222. $cursor = $this->find($condition, $fields, $options);
  223. $rows = $cursor->toArray();
  224. return empty($rows) ? null : current($rows);
  225. }
  226. /**
  227. * Updates a document and returns it.
  228. * @param array $condition query condition
  229. * @param array $update update criteria
  230. * @param array $options list of options in format: optionName => optionValue.
  231. * @return array|null the original document, or the modified document when $options['new'] is set.
  232. * @throws Exception on failure.
  233. */
  234. public function findAndModify($condition, $update, $options = [])
  235. {
  236. return $this->database->createCommand()->findAndModify($this->name, $condition, $update, $options);
  237. }
  238. /**
  239. * Inserts new data into collection.
  240. * @param array|object $data data to be inserted.
  241. * @param array $options list of options in format: optionName => optionValue.
  242. * @return \MongoDB\BSON\ObjectID new record ID instance.
  243. * @throws Exception on failure.
  244. */
  245. public function insert($data, $options = [])
  246. {
  247. return $this->database->createCommand()->insert($this->name, $data, $options);
  248. }
  249. /**
  250. * Inserts several new rows into collection.
  251. * @param array $rows array of arrays or objects to be inserted.
  252. * @param array $options list of options in format: optionName => optionValue.
  253. * @return array inserted data, each row will have "_id" key assigned to it.
  254. * @throws Exception on failure.
  255. */
  256. public function batchInsert($rows, $options = [])
  257. {
  258. $insertedIds = $this->database->createCommand()->batchInsert($this->name, $rows, $options);
  259. foreach ($rows as $key => $row) {
  260. $rows[$key]['_id'] = $insertedIds[$key];
  261. }
  262. return $rows;
  263. }
  264. /**
  265. * Updates the rows, which matches given criteria by given data.
  266. * Note: for "multi" mode Mongo requires explicit strategy "$set" or "$inc"
  267. * to be specified for the "newData". If no strategy is passed "$set" will be used.
  268. * @param array $condition description of the objects to update.
  269. * @param array $newData the object with which to update the matching records.
  270. * @param array $options list of options in format: optionName => optionValue.
  271. * @return int|bool number of updated documents or whether operation was successful.
  272. * @throws Exception on failure.
  273. */
  274. public function update($condition, $newData, $options = [])
  275. {
  276. $writeResult = $this->database->createCommand()->update($this->name, $condition, $newData, $options);
  277. return $writeResult->getModifiedCount() + $writeResult->getUpsertedCount();
  278. }
  279. /**
  280. * Update the existing database data, otherwise insert this data
  281. * @param array|object $data data to be updated/inserted.
  282. * @param array $options list of options in format: optionName => optionValue.
  283. * @return \MongoDB\BSON\ObjectID updated/new record id instance.
  284. * @throws Exception on failure.
  285. */
  286. public function save($data, $options = [])
  287. {
  288. if (empty($data['_id'])) {
  289. return $this->insert($data, $options);
  290. }
  291. $id = $data['_id'];
  292. unset($data['_id']);
  293. $this->update(['_id' => $id], ['$set' => $data], ['upsert' => true]);
  294. return is_object($id) ? $id : new ObjectID($id);
  295. }
  296. /**
  297. * Removes data from the collection.
  298. * @param array $condition description of records to remove.
  299. * @param array $options list of options in format: optionName => optionValue.
  300. * @return int|bool number of updated documents or whether operation was successful.
  301. * @throws Exception on failure.
  302. */
  303. public function remove($condition = [], $options = [])
  304. {
  305. $options = array_merge(['limit' => 0], $options);
  306. $writeResult = $this->database->createCommand()->delete($this->name, $condition, $options);
  307. return $writeResult->getDeletedCount();
  308. }
  309. /**
  310. * Counts records in this collection.
  311. * @param array $condition query condition
  312. * @param array $options list of options in format: optionName => optionValue.
  313. * @return int records count.
  314. * @since 2.1
  315. */
  316. public function count($condition = [], $options = [])
  317. {
  318. return $this->database->createCommand()->count($this->name, $condition, $options);
  319. }
  320. /**
  321. * Returns a list of distinct values for the given column across a collection.
  322. * @param string $column column to use.
  323. * @param array $condition query parameters.
  324. * @param array $options list of options in format: optionName => optionValue.
  325. * @return array|bool array of distinct values, or "false" on failure.
  326. * @throws Exception on failure.
  327. */
  328. public function distinct($column, $condition = [], $options = [])
  329. {
  330. return $this->database->createCommand()->distinct($this->name, $column, $condition, $options);
  331. }
  332. /**
  333. * Performs aggregation using Mongo Aggregation Framework.
  334. * In case 'cursor' option is specified [[\MongoDB\Driver\Cursor]] instance is returned,
  335. * otherwise - an array of aggregation results.
  336. * @param array $pipelines list of pipeline operators.
  337. * @param array $options optional parameters.
  338. * @return array|\MongoDB\Driver\Cursor the result of the aggregation.
  339. * @throws Exception on failure.
  340. */
  341. public function aggregate($pipelines, $options = [])
  342. {
  343. return $this->database->createCommand()->aggregate($this->name, $pipelines, $options);
  344. }
  345. /**
  346. * Performs aggregation using Mongo "group" command.
  347. * @param mixed $keys fields to group by. If an array or non-code object is passed,
  348. * it will be the key used to group results. If instance of [[\MongoDB\BSON\Javascript]] passed,
  349. * it will be treated as a function that returns the key to group by.
  350. * @param array $initial Initial value of the aggregation counter object.
  351. * @param \MongoDB\BSON\Javascript|string $reduce function that takes two arguments (the current
  352. * document and the aggregation to this point) and does the aggregation.
  353. * Argument will be automatically cast to [[\MongoDB\BSON\Javascript]].
  354. * @param array $options optional parameters to the group command. Valid options include:
  355. * - condition - criteria for including a document in the aggregation.
  356. * - finalize - function called once per unique key that takes the final output of the reduce function.
  357. * @return array the result of the aggregation.
  358. * @throws Exception on failure.
  359. */
  360. public function group($keys, $initial, $reduce, $options = [])
  361. {
  362. return $this->database->createCommand()->group($this->name, $keys, $initial, $reduce, $options);
  363. }
  364. /**
  365. * Performs aggregation using MongoDB "map-reduce" mechanism.
  366. * Note: this function will not return the aggregation result, instead it will
  367. * write it inside the another Mongo collection specified by "out" parameter.
  368. * For example:
  369. *
  370. * ```php
  371. * $customerCollection = Yii::$app->mongo->getCollection('customer');
  372. * $resultCollectionName = $customerCollection->mapReduce(
  373. * 'function () {emit(this.status, this.amount)}',
  374. * 'function (key, values) {return Array.sum(values)}',
  375. * 'mapReduceOut',
  376. * ['status' => 3]
  377. * );
  378. * $query = new Query();
  379. * $results = $query->from($resultCollectionName)->all();
  380. * ```
  381. *
  382. * @param \MongoDB\BSON\Javascript|string $map function, which emits map data from collection.
  383. * Argument will be automatically cast to [[\MongoDB\BSON\Javascript]].
  384. * @param \MongoDB\BSON\Javascript|string $reduce function that takes two arguments (the map key
  385. * and the map values) and does the aggregation.
  386. * Argument will be automatically cast to [[\MongoDB\BSON\Javascript]].
  387. * @param string|array $out output collection name. It could be a string for simple output
  388. * ('outputCollection'), or an array for parametrized output (['merge' => 'outputCollection']).
  389. * You can pass ['inline' => true] to fetch the result at once without temporary collection usage.
  390. * @param array $condition criteria for including a document in the aggregation.
  391. * @param array $options additional optional parameters to the mapReduce command. Valid options include:
  392. *
  393. * - sort: array, key to sort the input documents. The sort key must be in an existing index for this collection.
  394. * - limit: int, the maximum number of documents to return in the collection.
  395. * - finalize: \MongoDB\BSON\Javascript|string, function, which follows the reduce method and modifies the output.
  396. * - scope: array, specifies global variables that are accessible in the map, reduce and finalize functions.
  397. * - jsMode: bool, specifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions.
  398. * - verbose: bool, specifies whether to include the timing information in the result information.
  399. *
  400. * @return string|array the map reduce output collection name or output results.
  401. * @throws Exception on failure.
  402. */
  403. public function mapReduce($map, $reduce, $out, $condition = [], $options = [])
  404. {
  405. return $this->database->createCommand()->mapReduce($this->name, $map, $reduce, $out, $condition, $options);
  406. }
  407. }