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

namespace yii\mongo;

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

/**
15
 * Collection represents the Mongo collection information.
16 17 18 19
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
20
class Collection extends Object
21 22
{
	/**
23
	 * @var \MongoCollection Mongo collection instance.
24
	 */
25
	public $mongoCollection;
26 27

	/**
28
	 * Drops this collection.
29
	 */
30
	public function drop()
31
	{
32
		$this->mongoCollection->drop();
33
	}
Paul Klimov committed
34 35

	/**
36
	 * @param array $condition
Paul Klimov committed
37 38 39
	 * @param array $fields
	 * @return \MongoCursor
	 */
40
	public function find($condition = [], $fields = [])
Paul Klimov committed
41
	{
42
		return $this->mongoCollection->find($this->buildCondition($condition), $fields);
Paul Klimov committed
43 44 45
	}

	/**
46
	 * @param array $condition
Paul Klimov committed
47 48 49
	 * @param array $fields
	 * @return array
	 */
50
	public function findAll($condition = [], $fields = [])
Paul Klimov committed
51
	{
52
		$cursor = $this->find($condition, $fields);
Paul Klimov committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66
		$result = [];
		foreach ($cursor as $data) {
			$result[] = $data;
		}
		return $result;
	}

	/**
	 * 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.
	 */
67
	public function insert($data, $options = [])
Paul Klimov committed
68
	{
69
		$token = 'Inserting data into ' . $this->mongoCollection->getName();
Paul Klimov committed
70 71 72
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
73
			$options = array_merge(['w' => 1], $options);
74
			$this->tryResultError($this->mongoCollection->insert($data, $options));
Paul Klimov committed
75 76 77 78 79
			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);
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
		}
	}

	/**
	 * 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 = [])
	{
		$token = 'Inserting batch data into ' . $this->mongoCollection->getName();
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
96
			$options = array_merge(['w' => 1], $options);
97 98 99 100 101 102 103 104 105 106 107
			$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.
108
	 * @param array $condition description of the objects to update.
109 110
	 * @param array $newData the object with which to update the matching records.
	 * @param array $options list of options in format: optionName => optionValue.
111
	 * @return integer|boolean number of updated documents or whether operation was successful.
112 113
	 * @throws Exception on failure.
	 */
114
	public function update($condition, $newData, $options = [])
115 116 117 118 119
	{
		$token = 'Updating data in ' . $this->mongoCollection->getName();
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
120 121 122 123 124 125 126 127 128
			$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];
				}
			}
			$condition = $this->buildCondition($condition);
			$result = $this->mongoCollection->update($condition, $newData, $options);
129
			$this->tryResultError($result);
130
			Yii::endProfile($token, __METHOD__);
131 132 133 134 135
			if (is_array($result) && array_key_exists('n', $result)) {
				return $result['n'];
			} else {
				return true;
			}
136 137 138
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
Paul Klimov committed
139 140 141 142 143 144 145 146 147 148
		}
	}

	/**
	 * 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.
	 */
149
	public function save($data, $options = [])
Paul Klimov committed
150
	{
151
		$token = 'Saving data into ' . $this->mongoCollection->getName();
Paul Klimov committed
152 153 154
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
155
			$options = array_merge(['w' => 1], $options);
156
			$this->tryResultError($this->mongoCollection->save($data, $options));
Paul Klimov committed
157 158 159 160 161 162 163 164 165 166
			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.
167
	 * @param array $condition description of records to remove.
Paul Klimov committed
168
	 * @param array $options list of options in format: optionName => optionValue.
169
	 * @return integer|boolean number of updated documents or whether operation was successful.
Paul Klimov committed
170 171
	 * @throws Exception on failure.
	 */
172
	public function remove($condition = [], $options = [])
Paul Klimov committed
173
	{
174
		$token = 'Removing data from ' . $this->mongoCollection->getName();
Paul Klimov committed
175 176 177
		Yii::info($token, __METHOD__);
		try {
			Yii::beginProfile($token, __METHOD__);
178
			$options = array_merge(['w' => 1, 'multiple' => true], $options);
179 180
			$result = $this->mongoCollection->remove($this->buildCondition($condition), $options);
			$this->tryResultError($result);
Paul Klimov committed
181
			Yii::endProfile($token, __METHOD__);
182 183 184 185 186
			if (is_array($result) && array_key_exists('n', $result)) {
				return $result['n'];
			} else {
				return true;
			}
Paul Klimov committed
187 188 189 190 191 192
		} catch (\Exception $e) {
			Yii::endProfile($token, __METHOD__);
			throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
		}
	}

193 194 195 196 197 198 199 200 201 202 203 204
	/**
	 * 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.
	 */
	public function distinct($column, $condition = [])
	{
		return $this->mongoCollection->distinct($column, $this->buildCondition($condition));
	}

	/**
205 206 207 208 209
	 * Performs aggregation using Mongo Aggregation Framework.
	 * @param array $pipeline list of pipeline operators, or just the first operator
	 * @param array $pipelineOperator Additional pipeline operators
	 * @return array the result of the aggregation.
	 * @see http://docs.mongodb.org/manual/applications/aggregation/
210 211 212 213 214 215 216 217
	 */
	public function aggregate($pipeline, $pipelineOperator = [])
	{
		$args = func_get_args();
		return call_user_func_array([$this->mongoCollection, 'aggregate'], $args);
	}

	/**
218
	 * Performs aggregation using Mongo Map Reduce mechanism.
219
	 * @param mixed $keys
220 221 222 223 224 225 226 227
	 * @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.
228 229 230 231
	 */
	public function mapReduce($keys, $initial, $reduce, $options = [])
	{
		if (!($reduce instanceof \MongoCode)) {
232
			$reduce = new \MongoCode((string)$reduce);
233 234 235 236
		}
		if (array_key_exists('condition', $options)) {
			$options['condition'] = $this->buildCondition($options['condition']);
		}
237 238 239 240 241
		if (array_key_exists('finalize', $options)) {
			if (!($options['finalize'] instanceof \MongoCode)) {
				$options['finalize'] = new \MongoCode((string)$options['finalize']);
			}
		}
242 243 244
		return $this->mongoCollection->group($keys, $initial, $reduce, $options);
	}

Paul Klimov committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	/**
	 * 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)) {
			if (!empty($result['err'])) {
				throw new Exception($result['errmsg'], (int)$result['code']);
			}
		} elseif (!$result) {
			throw new Exception('Unknown error, use "w=1" option to enable error tracking');
		}
	}
260 261 262 263 264 265 266 267 268

	/**
	 * Converts user friendly condition keyword into actual Mongo condition keyword.
	 * @param string $key raw condition key.
	 * @return string actual key.
	 */
	protected function normalizeConditionKeyword($key)
	{
		static $map = [
269
			'OR' => '$or',
270 271 272 273 274 275
			'>' => '$gt',
			'>=' => '$gte',
			'<' => '$lt',
			'<=' => '$lte',
			'!=' => '$ne',
			'<>' => '$ne',
276 277 278 279 280 281 282 283 284
			'IN' => '$in',
			'NOT IN' => '$nin',
			'ALL' => '$all',
			'SIZE' => '$size',
			'TYPE' => '$type',
			'EXISTS' => '$exists',
			'NOTEXISTS' => '$exists',
			'ELEMMATCH' => '$elemMatch',
			'MOD' => '$mod',
285 286 287
			'%' => '$mod',
			'=' => '$$eq',
			'==' => '$$eq',
288
			'WHERE' => '$where'
289
		];
290 291 292
		$matchKey = strtoupper($key);
		if (array_key_exists($matchKey, $map)) {
			return $map[$matchKey];
293 294 295 296 297 298
		} else {
			return $key;
		}
	}

	/**
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	 * 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
328 329 330
	 */
	public function buildCondition($condition)
	{
331 332 333 334 335 336 337 338 339 340
		static $builders = [
			'AND' => 'buildAndCondition',
			'OR' => 'buildOrCondition',
			'BETWEEN' => 'buildBetweenCondition',
			'NOT BETWEEN' => 'buildBetweenCondition',
			'IN' => 'buildInCondition',
			'NOT IN' => 'buildInCondition',
			'LIKE' => 'buildLikeCondition',
		];

341 342
		if (!is_array($condition)) {
			throw new InvalidParamException('Condition should be an array.');
343 344
		} elseif (empty($condition)) {
			return [];
345
		}
346 347 348 349 350 351
		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);
352
			} else {
353
				throw new InvalidParamException('Found unknown operator in query: ' . $operator);
354
			}
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
		} 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) {
			$name = $this->normalizeConditionKeyword($name);
			if (strncmp('$', $name, 1) === 0) {
				// Native Mongo condition:
				$result[$name] = $value;
374
			} else {
375 376 377 378 379 380 381 382 383
				if (is_array($value)) {
					if (array_key_exists(0, $value)) {
						// Quick IN condition:
						$result = array_merge($result, $this->buildInCondition('IN', [$name, $value]));
					} else {
						// Normalize possible verbose condition:
						$actualValue = [];
						foreach ($value as $k => $v) {
							$actualValue[$this->normalizeConditionKeyword($k)] = $v;
384
						}
385
						$result[$name] = $actualValue;
386
					}
387
				} else {
388 389 390
					// Direct match:
					if ($name == '_id') {
						$value = $this->ensureMongoId($value);
391
					}
392
					$result[$name] = $value;
393
				}
394 395 396 397
			}
		}
		return $result;
	}
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

	/**
	 * 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;
		return [$column => '/' . $value . '/'];
	}
520
}