Collection.php 30.8 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\mongodb;
9

10
use yii\base\InvalidParamException;
11
use yii\base\Object;
Paul Klimov committed
12
use Yii;
Paul Klimov committed
13
use yii\helpers\Json;
14 15

/**
16
 * Collection represents the Mongo collection information.
17
 *
18 19 20 21 22 23
 * A collection object is usually created by calling [[Database::getCollection()]] or [[Connection::getCollection()]].
 *
 * Collection provides the basic interface for the Mongo queries, mostly: insert, update, delete operations.
 * For example:
 *
 * ~~~
24
 * $collection = Yii::$app->mongodb->getCollection('customer');
25 26 27
 * $collection->insert(['name' => 'John Smith', 'status' => 1]);
 * ~~~
 *
28 29
 * To perform "find" queries, please use [[Query]] instead.
 *
30 31 32 33 34 35
 * Mongo uses JSON format to specify query conditions with quite specific syntax.
 * However Collection class provides the ability of "translating" common condition format used "yii\db\*"
 * into Mongo condition.
 * For example:
 * ~~~
 * $condition = [
36 37 38 39 40
 *     [
 *         'OR',
 *         ['AND', ['first_name' => 'John'], ['last_name' => 'Smith']],
 *         ['status' => [1, 2, 3]]
 *     ],
41 42 43 44 45
 * ];
 * print_r($collection->buildCondition($condition));
 * // outputs :
 * [
 *     '$or' => [
46 47 48 49 50 51 52
 *         [
 *             'first_name' => 'John',
 *             'last_name' => 'John',
 *         ],
 *         [
 *             'status' => ['$in' => [1, 2, 3]],
 *         ]
53 54 55 56
 *     ]
 * ]
 * ~~~
 *
57
 * Note: condition values for the key '_id' will be automatically cast to [[\MongoId]] instance,
58
 * even if they are plain strings. However, if you have other columns, containing [[\MongoId]], you
59
 * should take care of possible typecast on your own.
60
 *
Qiang Xue committed
61 62 63 64
 * @property string $fullName Full name of this collection, including database name. This property is
 * read-only.
 * @property array $lastError Last error information. This property is read-only.
 * @property string $name Name of this collection. This property is read-only.
65
 *
66 67 68
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
69
class Collection extends Object
70 71
{
	/**
72
	 * @var \MongoCollection Mongo collection instance.
73
	 */
74
	public $mongoCollection;
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	/**
	 * @return string name of this collection.
	 */
	public function getName()
	{
		return $this->mongoCollection->getName();
	}

	/**
	 * @return string full name of this collection, including database name.
	 */
	public function getFullName()
	{
		return $this->mongoCollection->__toString();
	}

92 93 94 95 96 97 98 99
	/**
	 * @return array last error information.
	 */
	public function getLastError()
	{
		return $this->mongoCollection->db->lastError();
	}

Paul Klimov committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
	/**
	 * Composes log/profile token.
	 * @param string $command command name
	 * @param array $arguments command arguments.
	 * @return string token.
	 */
	protected function composeLogToken($command, $arguments = [])
	{
		$parts = [];
		foreach ($arguments as $argument) {
			$parts[] = is_scalar($argument) ? $argument : Json::encode($argument);
		}
		return $this->getFullName() . '.' . $command . '(' . implode(', ', $parts) . ')';
	}

115
	/**
116
	 * Drops this collection.
117 118
	 * @throws Exception on failure.
	 * @return boolean whether the operation successful.
119
	 */
120
	public function drop()
121
	{
Paul Klimov committed
122
		$token = $this->composeLogToken('drop');
123 124 125 126 127 128 129 130 131 132 133
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
			$result = $this->mongoCollection->drop();
			$this->tryResultError($result);
			Yii::endProfile($token, __METHOD__);
			return true;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
134
	}
Paul Klimov committed
135

136
	/**
137
	 * Creates an index on the collection and the specified fields.
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	 * @param array|string $columns column name or list of column names.
	 * If array is given, each element in the array has as key the field name, and as
	 * value either 1 for ascending sort, or -1 for descending sort.
	 * You can specify field using native numeric key with the field name as a value,
	 * in this case ascending sort will be used.
	 * For example:
	 * ~~~
	 * [
	 *     'name',
	 *     'status' => -1,
	 * ]
	 * ~~~
	 * @param array $options list of options in format: optionName => optionValue.
	 * @throws Exception on failure.
	 * @return boolean whether the operation successful.
	 */
	public function createIndex($columns, $options = [])
	{
		if (!is_array($columns)) {
			$columns = [$columns];
		}
Paul Klimov committed
159 160 161
		$keys = $this->normalizeIndexKeys($columns);
		$token = $this->composeLogToken('createIndex', [$keys, $options]);
		$options = array_merge(['w' => 1], $options);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
			$result = $this->mongoCollection->ensureIndex($keys, $options);
			$this->tryResultError($result);
			Yii::endProfile($token, __METHOD__);
			return true;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

	/**
	 * Drop indexes for specified column(s).
	 * @param string|array $columns column name or list of column names.
178 179
	 * If array is given, each element in the array has as key the field name, and as
	 * value either 1 for ascending sort, or -1 for descending sort.
180
	 * Use value 'text' to specify text index.
181 182 183 184 185 186 187
	 * You can specify field using native numeric key with the field name as a value,
	 * in this case ascending sort will be used.
	 * For example:
	 * ~~~
	 * [
	 *     'name',
	 *     'status' => -1,
188
	 *     'description' => 'text',
189 190 191 192
	 * ]
	 * ~~~
	 * @throws Exception on failure.
	 * @return boolean whether the operation successful.
193 194 195
	 */
	public function dropIndex($columns)
	{
196 197 198
		if (!is_array($columns)) {
			$columns = [$columns];
		}
Paul Klimov committed
199 200
		$keys = $this->normalizeIndexKeys($columns);
		$token = $this->composeLogToken('dropIndex', [$keys]);
201 202 203 204 205 206 207 208 209
		Yii::info($token, __METHOD__);
		try {
			$result = $this->mongoCollection->deleteIndex($keys);
			$this->tryResultError($result);
			return true;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
210 211 212
	}

	/**
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	 * Compose index keys from given columns/keys list.
	 * @param array $columns raw columns/keys list.
	 * @return array normalizes index keys array.
	 */
	protected function normalizeIndexKeys($columns)
	{
		$keys = [];
		foreach ($columns as $key => $value) {
			if (is_numeric($key)) {
				$keys[$value] = \MongoCollection::ASCENDING;
			} else {
				$keys[$key] = $value;
			}
		}
		return $keys;
	}

	/**
	 * Drops all indexes for this collection.
	 * @throws Exception on failure.
	 * @return integer count of dropped indexes.
234 235 236
	 */
	public function dropAllIndexes()
	{
Paul Klimov committed
237
		$token = $this->composeLogToken('dropIndexes');
238 239 240 241
		Yii::info($token, __METHOD__);
		try {
			$result = $this->mongoCollection->deleteIndexes();
			$this->tryResultError($result);
242
			return $result['nIndexesWas'];
243 244 245 246
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
247 248
	}

Paul Klimov committed
249
	/**
250 251 252 253 254 255
	 * Returns a cursor for the search results.
	 * In order to perform "find" queries use [[Query]] class.
	 * @param array $condition query condition
	 * @param array $fields fields to be selected
	 * @return \MongoCursor cursor for the search results
	 * @see Query
Paul Klimov committed
256
	 */
257
	public function find($condition = [], $fields = [])
Paul Klimov committed
258
	{
259
		return $this->mongoCollection->find($this->buildCondition($condition), $fields);
Paul Klimov committed
260 261
	}

262
	/**
263
	 * Returns a single document.
264 265 266 267 268 269 270 271 272 273
	 * @param array $condition query condition
	 * @param array $fields fields to be selected
	 * @return array|null the single document. Null is returned if the query results in nothing.
	 * @see http://www.php.net/manual/en/mongocollection.findone.php
	 */
	public function findOne($condition = [], $fields = [])
	{
		return $this->mongoCollection->findOne($this->buildCondition($condition), $fields);
	}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
	/**
	 * Updates a document and returns it.
	 * @param array $condition query condition
	 * @param array $update update criteria
	 * @param array $fields fields to be returned
	 * @param array $options list of options in format: optionName => optionValue.
	 * @return array|null the original document, or the modified document when $options['new'] is set.
	 * @throws Exception on failure.
	 * @see http://www.php.net/manual/en/mongocollection.findandmodify.php
	 */
	public function findAndModify($condition, $update, $fields = [], $options = [])
	{
		$condition = $this->buildCondition($condition);
		$token = $this->composeLogToken('findAndModify', [$condition, $update, $fields, $options]);
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
			$result = $this->mongoCollection->findAndModify($condition, $update, $fields, $options);
			Yii::endProfile($token, __METHOD__);
			return $result;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

Paul Klimov committed
300 301 302 303 304 305 306
	/**
	 * Inserts new data into collection.
	 * @param array|object $data data to be inserted.
	 * @param array $options list of options in format: optionName => optionValue.
	 * @return \MongoId new record id instance.
	 * @throws Exception on failure.
	 */
307
	public function insert($data, $options = [])
Paul Klimov committed
308
	{
Paul Klimov committed
309
		$token = $this->composeLogToken('insert', [$data]);
Paul Klimov committed
310 311 312
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
313
			$options = array_merge(['w' => 1], $options);
314
			$this->tryResultError($this->mongoCollection->insert($data, $options));
Paul Klimov committed
315 316 317 318 319
			Yii::endProfile($token, __METHOD__);
			return is_array($data) ? $data['_id'] : $data->_id;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
320 321 322 323 324 325 326 327 328 329 330 331
		}
	}

	/**
	 * Inserts several new rows into collection.
	 * @param array $rows array of arrays or objects to be inserted.
	 * @param array $options list of options in format: optionName => optionValue.
	 * @return array inserted data, each row will have "_id" key assigned to it.
	 * @throws Exception on failure.
	 */
	public function batchInsert($rows, $options = [])
	{
Paul Klimov committed
332
		$token = $this->composeLogToken('batchInsert', [$rows]);
333 334 335
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
336
			$options = array_merge(['w' => 1], $options);
337 338 339 340 341 342 343 344 345 346 347
			$this->tryResultError($this->mongoCollection->batchInsert($rows, $options));
			Yii::endProfile($token, __METHOD__);
			return $rows;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

	/**
	 * Updates the rows, which matches given criteria by given data.
348 349
	 * Note: for "multiple" mode Mongo requires explicit strategy "$set" or "$inc"
	 * to be specified for the "newData". If no strategy is passed "$set" will be used.
350
	 * @param array $condition description of the objects to update.
351 352
	 * @param array $newData the object with which to update the matching records.
	 * @param array $options list of options in format: optionName => optionValue.
353
	 * @return integer|boolean number of updated documents or whether operation was successful.
354 355
	 * @throws Exception on failure.
	 */
356
	public function update($condition, $newData, $options = [])
357
	{
Paul Klimov committed
358 359 360 361 362 363 364 365 366
		$condition = $this->buildCondition($condition);
		$options = array_merge(['w' => 1, 'multiple' => true], $options);
		if ($options['multiple']) {
			$keys = array_keys($newData);
			if (!empty($keys) && strncmp('$', $keys[0], 1) !== 0) {
				$newData = ['$set' => $newData];
			}
		}
		$token = $this->composeLogToken('update', [$condition, $newData, $options]);
367 368 369
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
370
			$result = $this->mongoCollection->update($condition, $newData, $options);
371
			$this->tryResultError($result);
372
			Yii::endProfile($token, __METHOD__);
373 374 375 376 377
			if (is_array($result) && array_key_exists('n', $result)) {
				return $result['n'];
			} else {
				return true;
			}
378 379 380
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
Paul Klimov committed
381 382 383 384 385 386 387 388 389 390
		}
	}

	/**
	 * Update the existing database data, otherwise insert this data
	 * @param array|object $data data to be updated/inserted.
	 * @param array $options list of options in format: optionName => optionValue.
	 * @return \MongoId updated/new record id instance.
	 * @throws Exception on failure.
	 */
391
	public function save($data, $options = [])
Paul Klimov committed
392
	{
Paul Klimov committed
393
		$token = $this->composeLogToken('save', [$data]);
Paul Klimov committed
394 395 396
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
397
			$options = array_merge(['w' => 1], $options);
398
			$this->tryResultError($this->mongoCollection->save($data, $options));
Paul Klimov committed
399 400 401 402 403 404 405 406 407 408
			Yii::endProfile($token, __METHOD__);
			return is_array($data) ? $data['_id'] : $data->_id;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

	/**
	 * Removes data from the collection.
409
	 * @param array $condition description of records to remove.
Paul Klimov committed
410
	 * @param array $options list of options in format: optionName => optionValue.
411
	 * @return integer|boolean number of updated documents or whether operation was successful.
Paul Klimov committed
412
	 * @throws Exception on failure.
413
	 * @see http://www.php.net/manual/en/mongocollection.remove.php
Paul Klimov committed
414
	 */
415
	public function remove($condition = [], $options = [])
Paul Klimov committed
416
	{
Paul Klimov committed
417
		$condition = $this->buildCondition($condition);
418
		$options = array_merge(['w' => 1, 'justOne' => false], $options);
Paul Klimov committed
419
		$token = $this->composeLogToken('remove', [$condition, $options]);
Paul Klimov committed
420 421 422
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
Paul Klimov committed
423
			$result = $this->mongoCollection->remove($condition, $options);
424
			$this->tryResultError($result);
Paul Klimov committed
425
			Yii::endProfile($token, __METHOD__);
426 427 428 429 430
			if (is_array($result) && array_key_exists('n', $result)) {
				return $result['n'];
			} else {
				return true;
			}
Paul Klimov committed
431 432 433 434 435 436
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

437 438 439 440 441
	/**
	 * Returns a list of distinct values for the given column across a collection.
	 * @param string $column column to use.
	 * @param array $condition query parameters.
	 * @return array|boolean array of distinct values, or "false" on failure.
Paul Klimov committed
442
	 * @throws Exception on failure.
443 444 445
	 */
	public function distinct($column, $condition = [])
	{
Paul Klimov committed
446 447
		$condition = $this->buildCondition($condition);
		$token = $this->composeLogToken('distinct', [$column, $condition]);
448
		Yii::info($token, __METHOD__);
Paul Klimov committed
449 450 451 452 453 454 455 456 457
		try {
			Yii::beginProfile($token, __METHOD__);
			$result = $this->mongoCollection->distinct($column, $condition);
			Yii::endProfile($token, __METHOD__);
			return $result;
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
458 459 460
	}

	/**
461 462
	 * Performs aggregation using Mongo Aggregation Framework.
	 * @param array $pipeline list of pipeline operators, or just the first operator
463 464
	 * @param array $pipelineOperator additional pipeline operator. You can specify additional
	 * pipelines via third argument, fourth argument etc.
465
	 * @return array the result of the aggregation.
466
	 * @throws Exception on failure.
467
	 * @see http://docs.mongodb.org/manual/applications/aggregation/
468 469 470
	 */
	public function aggregate($pipeline, $pipelineOperator = [])
	{
471 472
		$args = func_get_args();
		$token = $this->composeLogToken('aggregate', $args);
473
		Yii::info($token, __METHOD__);
474 475 476 477 478 479 480 481 482 483
		try {
			Yii::beginProfile($token, __METHOD__);
			$result = call_user_func_array([$this->mongoCollection, 'aggregate'], $args);
			$this->tryResultError($result);
			Yii::endProfile($token, __METHOD__);
			return $result['result'];
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
484 485 486
	}

	/**
487
	 * Performs aggregation using Mongo "group" command.
488 489 490
	 * @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. If instance of [[\MongoCode]] passed,
	 * it will be treated as a function that returns the key to group by.
491 492 493 494 495 496 497 498
	 * @param array $initial Initial value of the aggregation counter object.
	 * @param \MongoCode|string $reduce function that takes two arguments (the current
	 * document and the aggregation to this point) and does the aggregation.
	 * Argument will be automatically cast to [[\MongoCode]].
	 * @param array $options optional parameters to the group command. Valid options include:
	 *  - condition - criteria for including a document in the aggregation.
	 *  - finalize - function called once per unique key that takes the final output of the reduce function.
	 * @return array the result of the aggregation.
499
	 * @throws Exception on failure.
500
	 * @see http://docs.mongodb.org/manual/reference/command/group/
501
	 */
502
	public function group($keys, $initial, $reduce, $options = [])
503
	{
Paul Klimov committed
504 505 506 507 508 509 510 511 512 513 514 515
		if (!($reduce instanceof \MongoCode)) {
			$reduce = new \MongoCode((string)$reduce);
		}
		if (array_key_exists('condition', $options)) {
			$options['condition'] = $this->buildCondition($options['condition']);
		}
		if (array_key_exists('finalize', $options)) {
			if (!($options['finalize'] instanceof \MongoCode)) {
				$options['finalize'] = new \MongoCode((string)$options['finalize']);
			}
		}
		$token = $this->composeLogToken('group', [$keys, $initial, $reduce, $options]);
516
		Yii::info($token, __METHOD__);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
		try {
			Yii::beginProfile($token, __METHOD__);
			// Avoid possible E_DEPRECATED for $options:
			if (empty($options)) {
				$result = $this->mongoCollection->group($keys, $initial, $reduce);
			} else {
				$result = $this->mongoCollection->group($keys, $initial, $reduce, $options);
			}
			$this->tryResultError($result);

			Yii::endProfile($token, __METHOD__);
			if (array_key_exists('retval', $result)) {
				return $result['retval'];
			} else {
				return [];
			}
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
536
		}
537
	}
538

539 540 541 542
	/**
	 * Performs aggregation using Mongo "map reduce" mechanism.
	 * Note: this function will not return the aggregation result, instead it will
	 * write it inside the another Mongo collection specified by "out" parameter.
543 544 545 546 547 548 549 550 551 552 553 554 555 556
	 * For example:
	 *
	 * ~~~
	 * $customerCollection = Yii::$app->mongo->getCollection('customer');
	 * $resultCollectionName = $customerCollection->mapReduce(
	 *     'function () {emit(this.status, this.amount)}',
	 *     'function (key, values) {return Array.sum(values)}',
	 *     'mapReduceOut',
	 *     ['status' => 3]
	 * );
	 * $query = new Query();
	 * $results = $query->from($resultCollectionName)->all();
	 * ~~~
	 *
557 558 559 560 561 562
	 * @param \MongoCode|string $map function, which emits map data from collection.
	 * Argument will be automatically cast to [[\MongoCode]].
	 * @param \MongoCode|string $reduce function that takes two arguments (the map key
	 * and the map values) and does the aggregation.
	 * Argument will be automatically cast to [[\MongoCode]].
	 * @param string|array $out output collection name. It could be a string for simple output
563
	 * ('outputCollection'), or an array for parametrized output (['merge' => 'outputCollection']).
564
	 * You can pass ['inline' => true] to fetch the result at once without temporary collection usage.
565
	 * @param array $condition criteria for including a document in the aggregation.
566 567 568 569 570 571 572
	 * @param array $options additional optional parameters to the mapReduce command. Valid options include:
	 *  - sort - array - key to sort the input documents. The sort key must be in an existing index for this collection.
	 *  - limit - the maximum number of documents to return in the collection.
	 *  - finalize - function, which follows the reduce method and modifies the output.
	 *  - scope - array - specifies global variables that are accessible in the map, reduce and finalize functions.
	 *  - jsMode - boolean -Specifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions.
	 *  - verbose - boolean - specifies whether to include the timing information in the result information.
573
	 * @return string|array the map reduce output collection name or output results.
574 575
	 * @throws Exception on failure.
	 */
576
	public function mapReduce($map, $reduce, $out, $condition = [], $options = [])
577
	{
Paul Klimov committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
		if (!($map instanceof \MongoCode)) {
			$map = new \MongoCode((string)$map);
		}
		if (!($reduce instanceof \MongoCode)) {
			$reduce = new \MongoCode((string)$reduce);
		}
		$command = [
			'mapReduce' => $this->getName(),
			'map' => $map,
			'reduce' => $reduce,
			'out' => $out
		];
		if (!empty($condition)) {
			$command['query'] = $this->buildCondition($condition);
		}
593 594 595 596 597 598 599 600
		if (array_key_exists('finalize', $options)) {
			if (!($options['finalize'] instanceof \MongoCode)) {
				$options['finalize'] = new \MongoCode((string)$options['finalize']);
			}
		}
		if (!empty($options)) {
			$command = array_merge($command, $options);
		}
Paul Klimov committed
601 602
		$token = $this->composeLogToken('mapReduce', [$map, $reduce, $out]);
		Yii::info($token, __METHOD__);
603 604
		try {
			Yii::beginProfile($token, __METHOD__);
Paul Klimov committed
605
			$command = array_merge(['mapReduce' => $this->getName()], $command);
606 607 608
			$result = $this->mongoCollection->db->command($command);
			$this->tryResultError($result);
			Yii::endProfile($token, __METHOD__);
609
			return array_key_exists('results', $result) ? $result['results'] : $result['result'];
610 611 612
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
613
		}
614 615
	}

616 617 618 619 620
	/**
	 * Performs full text search.
	 * @param string $search string of terms that MongoDB parses and uses to query the text index.
	 * @param array $condition criteria for filtering a results list.
	 * @param array $fields list of fields to be returned in result.
621 622 623
	 * @param array $options additional optional parameters to the mapReduce command. Valid options include:
	 *  - limit - the maximum number of documents to include in the response (by default 100).
	 *  - language - the language that determines the list of stop words for the search
624 625 626 627 628
	 * and the rules for the stemmer and tokenizer. If not specified, the search uses the default
	 * language of the index.
	 * @return array the highest scoring documents, in descending order by score.
	 * @throws Exception on failure.
	 */
629
	public function fullTextSearch($search, $condition = [], $fields = [], $options = []) {
630 631 632 633 634 635 636 637 638
		$command = [
			'search' => $search
		];
		if (!empty($condition)) {
			$command['filter'] = $this->buildCondition($condition);
		}
		if (!empty($fields)) {
			$command['project'] = $fields;
		}
639 640
		if (!empty($options)) {
			$command = array_merge($command, $options);
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
		}
		$token = $this->composeLogToken('text', $command);
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
			$command = array_merge(['text' => $this->getName()], $command);
			$result = $this->mongoCollection->db->command($command);
			$this->tryResultError($result);
			Yii::endProfile($token, __METHOD__);
			return $result['results'];
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

Paul Klimov committed
657 658 659 660 661 662 663 664
	/**
	 * Checks if command execution result ended with an error.
	 * @param mixed $result raw command execution result.
	 * @throws Exception if an error occurred.
	 */
	protected function tryResultError($result)
	{
		if (is_array($result)) {
665 666 667 668 669 670 671 672 673 674 675 676 677 678
			if (!empty($result['errmsg'])) {
				$errorMessage = $result['errmsg'];
			} elseif (!empty($result['err'])) {
				$errorMessage = $result['err'];
			}
			if (isset($errorMessage)) {
				if (array_key_exists('code', $result)) {
					$errorCode = (int)$result['code'];
				} elseif (array_key_exists('ok', $result)) {
					$errorCode = (int)$result['ok'];
				} else {
					$errorCode = 0;
				}
				throw new Exception($errorMessage, $errorCode);
Paul Klimov committed
679 680 681 682 683
			}
		} elseif (!$result) {
			throw new Exception('Unknown error, use "w=1" option to enable error tracking');
		}
	}
684

685 686 687 688 689 690 691 692 693
	/**
	 * Throws an exception if there was an error on the last operation.
	 * @throws Exception if an error occurred.
	 */
	protected function tryLastError()
	{
		$this->tryResultError($this->getLastError());
	}

694
	/**
695
	 * Converts "\yii\db\*" quick condition keyword into actual Mongo condition keyword.
696 697 698 699 700 701
	 * @param string $key raw condition key.
	 * @return string actual key.
	 */
	protected function normalizeConditionKeyword($key)
	{
		static $map = [
702 703 704
			'OR' => '$or',
			'IN' => '$in',
			'NOT IN' => '$nin',
705
		];
706 707 708
		$matchKey = strtoupper($key);
		if (array_key_exists($matchKey, $map)) {
			return $map[$matchKey];
709 710 711 712 713 714
		} else {
			return $key;
		}
	}

	/**
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
	 * Converts given value into [[MongoId]] instance.
	 * If array given, each element of it will be processed.
	 * @param mixed $rawId raw id(s).
	 * @return array|\MongoId normalized id(s).
	 */
	protected function ensureMongoId($rawId)
	{
		if (is_array($rawId)) {
			$result = [];
			foreach ($rawId as $key => $value) {
				$result[$key] = $this->ensureMongoId($value);
			}
			return $result;
		} elseif (is_object($rawId)) {
			if ($rawId instanceof \MongoId) {
				return $rawId;
			} else {
				$rawId = (string)$rawId;
			}
		}
		return new \MongoId($rawId);
	}

	/**
	 * Parses the condition specification and generates the corresponding Mongo condition.
	 * @param array $condition the condition specification. Please refer to [[Query::where()]]
	 * on how to specify a condition.
	 * @return array the generated Mongo condition
	 * @throws InvalidParamException if the condition is in bad format
744 745 746
	 */
	public function buildCondition($condition)
	{
747 748 749 750 751 752 753 754 755 756
		static $builders = [
			'AND' => 'buildAndCondition',
			'OR' => 'buildOrCondition',
			'BETWEEN' => 'buildBetweenCondition',
			'NOT BETWEEN' => 'buildBetweenCondition',
			'IN' => 'buildInCondition',
			'NOT IN' => 'buildInCondition',
			'LIKE' => 'buildLikeCondition',
		];

757 758
		if (!is_array($condition)) {
			throw new InvalidParamException('Condition should be an array.');
759 760
		} elseif (empty($condition)) {
			return [];
761
		}
762 763 764 765 766 767
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
			$operator = strtoupper($condition[0]);
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
				return $this->$method($operator, $condition);
768
			} else {
769
				throw new InvalidParamException('Found unknown operator in query: ' . $operator);
770
			}
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
		} else {
			// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
			return $this->buildHashCondition($condition);
		}
	}

	/**
	 * Creates a condition based on column-value pairs.
	 * @param array $condition the condition specification.
	 * @return array the generated Mongo condition.
	 */
	public function buildHashCondition($condition)
	{
		$result = [];
		foreach ($condition as $name => $value) {
			if (strncmp('$', $name, 1) === 0) {
				// Native Mongo condition:
				$result[$name] = $value;
789
			} else {
790 791 792 793 794
				if (is_array($value)) {
					if (array_key_exists(0, $value)) {
						// Quick IN condition:
						$result = array_merge($result, $this->buildInCondition('IN', [$name, $value]));
					} else {
795 796
						// Mongo complex condition:
						$result[$name] = $value;
797
					}
798
				} else {
799 800 801
					// Direct match:
					if ($name == '_id') {
						$value = $this->ensureMongoId($value);
802
					}
803
					$result[$name] = $value;
804
				}
805 806 807 808
			}
		}
		return $result;
	}
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

	/**
	 * Connects two or more conditions with the `AND` operator.
	 * @param string $operator the operator to use for connecting the given operands
	 * @param array $operands the Mongo conditions to connect.
	 * @return array the generated Mongo condition.
	 */
	public function buildAndCondition($operator, $operands)
	{
		$result = [];
		foreach ($operands as $operand) {
			$condition = $this->buildCondition($operand);
			$result = array_merge_recursive($result, $condition);
		}
		return $result;
	}

	/**
	 * Connects two or more conditions with the `OR` operator.
	 * @param string $operator the operator to use for connecting the given operands
	 * @param array $operands the Mongo conditions to connect.
	 * @return array the generated Mongo condition.
	 */
	public function buildOrCondition($operator, $operands)
	{
		$operator = $this->normalizeConditionKeyword($operator);
		$parts = [];
		foreach ($operands as $operand) {
			$parts[] = $this->buildCondition($operand);
		}
		return [$operator => $parts];
	}

	/**
	 * Creates an Mongo condition, which emulates the `BETWEEN` operator.
	 * @param string $operator the operator to use
	 * @param array $operands the first operand is the column name. The second and third operands
	 * describe the interval that column value should be in.
	 * @return array the generated Mongo condition.
	 * @throws InvalidParamException if wrong number of operands have been given.
	 */
	public function buildBetweenCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
			throw new InvalidParamException("Operator '$operator' requires three operands.");
		}
		list($column, $value1, $value2) = $operands;
		if (strncmp('NOT', $operator, 3) === 0) {
			return [
				$column => [
					'$lt' => $value1,
					'$gt' => $value2,
				]
			];
		} else {
			return [
				$column => [
					'$gte' => $value1,
					'$lte' => $value2,
				]
			];
		}
	}

	/**
	 * Creates an Mongo condition with the `IN` operator.
	 * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
	 * @param array $operands the first operand is the column name. If it is an array
	 * a composite IN condition will be generated.
	 * The second operand is an array of values that column value should be among.
	 * @return array the generated Mongo condition.
	 * @throws InvalidParamException if wrong number of operands have been given.
	 */
	public function buildInCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new InvalidParamException("Operator '$operator' requires two operands.");
		}

		list($column, $values) = $operands;

		$values = (array)$values;

		if (!is_array($column)) {
			$columns = [$column];
			$values = [$column => $values];
		} elseif (count($column) < 2) {
			$columns = $column;
			$values = [$column[0] => $values];
		} else {
			$columns = $column;
		}

		$operator = $this->normalizeConditionKeyword($operator);
		$result = [];
		foreach ($columns as $column) {
			if ($column == '_id') {
				$inValues = $this->ensureMongoId($values[$column]);
			} else {
				$inValues = $values[$column];
			}
			$result[$column][$operator] = $inValues;
		}
		return $result;
	}

	/**
	 * Creates a Mongo condition, which emulates the `LIKE` operator.
	 * @param string $operator the operator to use
	 * @param array $operands the first operand is the column name.
	 * The second operand is a single value that column value should be compared with.
	 * @return array the generated Mongo condition.
	 * @throws InvalidParamException if wrong number of operands have been given.
	 */
	public function buildLikeCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new InvalidParamException("Operator '$operator' requires two operands.");
		}
		list($column, $value) = $operands;
929 930 931 932
		if (!($value instanceof \MongoRegex)) {
			$value = new \MongoRegex($value);
		}
		return [$column => $value];
933
	}
934
}