Class yii\mongodb\Collection
Inheritance | yii\mongodb\Collection » yii\base\Object |
---|---|
Subclasses | yii\mongodb\file\Collection |
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-mongodb/blob/master/Collection.php |
Collection represents the Mongo collection information.
A collection object is usually created by calling yii\mongodb\Database::getCollection() or yii\mongodb\Connection::getCollection().
Collection provides the basic interface for the Mongo queries, mostly: insert, update, delete operations. For example:
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
To perform "find" queries, please use yii\mongodb\Query instead.
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 = [
[
'OR',
['AND', ['first_name' => 'John'], ['last_name' => 'Smith']],
['status' => [1, 2, 3]]
],
];
print_r($collection->buildCondition($condition));
// outputs :
[
'$or' => [
[
'first_name' => 'John',
'last_name' => 'John',
],
[
'status' => ['$in' => [1, 2, 3]],
]
]
]
Note: condition values for the key '_id' will be automatically cast to \MongoId instance, even if they are plain strings. However, if you have other columns, containing \MongoId, you should take care of possible typecast on your own.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$fullName | string | Full name of this collection, including database name. | yii\mongodb\Collection |
$lastError | array | Last error information. | yii\mongodb\Collection |
$mongoCollection | \MongoCollection | Mongo collection instance. | yii\mongodb\Collection |
$name | string | Name of this collection. | yii\mongodb\Collection |
Public Methods
Method | Description | Defined By |
---|---|---|
aggregate() | Performs aggregation using Mongo Aggregation Framework. | yii\mongodb\Collection |
batchInsert() | Inserts several new rows into collection. | yii\mongodb\Collection |
buildAndCondition() | Connects two or more conditions with the AND operator. |
yii\mongodb\Collection |
buildBetweenCondition() | Creates an Mongo condition, which emulates the BETWEEN operator. |
yii\mongodb\Collection |
buildCondition() | Parses the condition specification and generates the corresponding Mongo condition. | yii\mongodb\Collection |
buildHashCondition() | Creates a condition based on column-value pairs. | yii\mongodb\Collection |
buildInCondition() | Creates an Mongo condition with the IN operator. |
yii\mongodb\Collection |
buildLikeCondition() | Creates a Mongo condition, which emulates the LIKE operator. |
yii\mongodb\Collection |
buildNotCondition() | Composes NOT condition. |
yii\mongodb\Collection |
buildOrCondition() | Connects two or more conditions with the OR operator. |
yii\mongodb\Collection |
buildRegexCondition() | Creates a Mongo regular expression condition. | yii\mongodb\Collection |
buildSimpleCondition() | Creates an Mongo condition like {$operator:{field:value}} . |
yii\mongodb\Collection |
createIndex() | Creates an index on the collection and the specified fields. | yii\mongodb\Collection |
distinct() | Returns a list of distinct values for the given column across a collection. | yii\mongodb\Collection |
drop() | Drops this collection. | yii\mongodb\Collection |
dropAllIndexes() | Drops all indexes for this collection. | yii\mongodb\Collection |
dropIndex() | Drop indexes for specified column(s). | yii\mongodb\Collection |
find() | Returns a cursor for the search results. | yii\mongodb\Collection |
findAndModify() | Updates a document and returns it. | yii\mongodb\Collection |
findOne() | Returns a single document. | yii\mongodb\Collection |
fullTextSearch() | Performs full text search. | yii\mongodb\Collection |
getFullName() | yii\mongodb\Collection | |
getLastError() | yii\mongodb\Collection | |
getName() | yii\mongodb\Collection | |
group() | Performs aggregation using Mongo "group" command. | yii\mongodb\Collection |
insert() | Inserts new data into collection. | yii\mongodb\Collection |
mapReduce() | Performs aggregation using Mongo "map reduce" mechanism. | yii\mongodb\Collection |
remove() | Removes data from the collection. | yii\mongodb\Collection |
save() | Update the existing database data, otherwise insert this data | yii\mongodb\Collection |
update() | Updates the rows, which matches given criteria by given data. | yii\mongodb\Collection |
Protected Methods
Method | Description | Defined By |
---|---|---|
composeLogToken() | Composes log/profile token. | yii\mongodb\Collection |
encodeLogData() | Encodes complex log data into JSON format string. | yii\mongodb\Collection |
ensureMongoId() | Converts given value into MongoId instance. | yii\mongodb\Collection |
normalizeConditionKeyword() | Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword. | yii\mongodb\Collection |
normalizeIndexKeys() | Compose index keys from given columns/keys list. | yii\mongodb\Collection |
processLogData() | Pre-processes the log data before sending it to json_encode() . |
yii\mongodb\Collection |
tryLastError() | Throws an exception if there was an error on the last operation. | yii\mongodb\Collection |
tryResultError() | Checks if command execution result ended with an error. | yii\mongodb\Collection |
Property Details
Full name of this collection, including database name. This property is read-only.
Last error information. This property is read-only.
Mongo collection instance.
Method Details
Performs aggregation using Mongo Aggregation Framework.
See also http://docs.mongodb.org/manual/applications/aggregation/.
public array aggregate ( $pipeline, $pipelineOperator = [] ) | ||
$pipeline | array |
List of pipeline operators, or just the first operator |
$pipelineOperator | array |
Additional pipeline operator. You can specify additional pipelines via third argument, fourth argument etc. |
return | array |
The result of the aggregation. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function aggregate($pipeline, $pipelineOperator = [])
{
$args = func_get_args();
$token = $this->composeLogToken('aggregate', $args);
Yii::info($token, __METHOD__);
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);
}
}
Inserts several new rows into collection.
public array batchInsert ( $rows, $options = [] ) | ||
$rows | array |
Array of arrays or objects to be inserted. |
$options | array |
List of options in format: optionName => optionValue. |
return | array |
Inserted data, each row will have "_id" key assigned to it. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function batchInsert($rows, $options = [])
{
$token = $this->composeLogToken('batchInsert', [$rows]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$options = array_merge(['w' => 1], $options);
$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);
}
}
Connects two or more conditions with the AND
operator.
public array buildAndCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use for connecting the given operands |
$operands | array |
The Mongo conditions to connect. |
return | array |
The generated Mongo condition. |
---|
public function buildAndCondition($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.
public array buildBetweenCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use |
$operands | array |
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 | \yii\base\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,
]
];
}
}
Parses the condition specification and generates the corresponding Mongo condition.
public array buildCondition ( $condition ) | ||
$condition | array |
The condition specification. Please refer to Query::where() on how to specify a condition. |
return | array |
The generated Mongo condition |
---|---|---|
throws | \yii\base\InvalidParamException |
if the condition is in bad format |
public function buildCondition($condition)
{
static $builders = [
'NOT' => 'buildNotCondition',
'AND' => 'buildAndCondition',
'OR' => 'buildOrCondition',
'BETWEEN' => 'buildBetweenCondition',
'NOT BETWEEN' => 'buildBetweenCondition',
'IN' => 'buildInCondition',
'NOT IN' => 'buildInCondition',
'REGEX' => 'buildRegexCondition',
'LIKE' => 'buildLikeCondition',
];
if (!is_array($condition)) {
throw new InvalidParamException('Condition should be an array.');
} elseif (empty($condition)) {
return [];
}
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = strtoupper($condition[0]);
if (isset($builders[$operator])) {
$method = $builders[$operator];
} else {
$operator = $condition[0];
$method = 'buildSimpleCondition';
}
array_shift($condition);
return $this->$method($operator, $condition);
} else {
// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return $this->buildHashCondition($condition);
}
}
Creates a condition based on column-value pairs.
public array buildHashCondition ( $condition ) | ||
$condition | array |
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;
} else {
if (is_array($value)) {
if (ArrayHelper::isIndexed($value)) {
// Quick IN condition:
$result = array_merge($result, $this->buildInCondition('IN', [$name, $value]));
} else {
// Mongo complex condition:
$result[$name] = $value;
}
} else {
// Direct match:
if ($name == '_id') {
$value = $this->ensureMongoId($value);
}
$result[$name] = $value;
}
}
}
return $result;
}
Creates an Mongo condition with the IN
operator.
public array buildInCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use (e.g. |
$operands | array |
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 | \yii\base\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;
$operator = $this->normalizeConditionKeyword($operator);
if (!is_array($column)) {
$columns = [$column];
$values = [$column => $values];
} elseif (count($column) > 1) {
return $this->buildCompositeInCondition($operator, $column, $values);
} else {
$columns = $column;
$values = [$column[0] => $values];
}
$result = [];
foreach ($columns as $column) {
if ($column == '_id') {
$inValues = $this->ensureMongoId($values[$column]);
} else {
$inValues = $values[$column];
}
$inValues = array_values($inValues);
if (count($inValues) === 1 && $operator === '$in') {
$result[$column] = $inValues[0];
} else {
$result[$column][$operator] = $inValues;
}
}
return $result;
}
Creates a Mongo condition, which emulates the LIKE
operator.
public array buildLikeCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use |
$operands | array |
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 | \yii\base\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;
if (!($value instanceof \MongoRegex)) {
$value = new \MongoRegex('/' . preg_quote($value) . '/i');
}
return [$column => $value];
}
Composes NOT
condition.
public array buildNotCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use for connecting the given operands |
$operands | array |
The Mongo conditions to connect. |
return | array |
The generated Mongo condition. |
---|---|---|
throws | \yii\base\InvalidParamException |
if wrong number of operands have been given. |
public function buildNotCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($name, $value) = $operands;
$result = [];
if (is_array($value)) {
$result[$name] = ['$not' => $this->buildCondition($value)];
} else {
if ($name == '_id') {
$value = $this->ensureMongoId($value);
}
$result[$name] = ['$ne' => $value];
}
return $result;
}
Connects two or more conditions with the OR
operator.
public array buildOrCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use for connecting the given operands |
$operands | array |
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 a Mongo regular expression condition.
public array buildRegexCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use |
$operands | array |
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 | \yii\base\InvalidParamException |
if wrong number of operands have been given. |
public function buildRegexCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (!($value instanceof \MongoRegex)) {
$value = new \MongoRegex($value);
}
return [$column => $value];
}
Creates an Mongo condition like {$operator:{field:value}}
.
public string buildSimpleCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use. Besides regular MongoDB operators, aliases like |
$operands | array |
The first operand is the column name. The second operand is a single value that column value should be compared with. |
return | string |
The generated Mongo condition. |
---|---|---|
throws | \yii\base\InvalidParamException |
if wrong number of operands have been given. |
public function buildSimpleCondition($operator, $operands)
{
if (count($operands) !== 2) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (strncmp('$', $operator, 1) !== 0) {
static $operatorMap = [
'>' => '$gt',
'<' => '$lt',
'>=' => '$gte',
'<=' => '$lte',
'!=' => '$ne',
'<>' => '$ne',
'=' => '$eq',
'==' => '$eq',
];
if (isset($operatorMap[$operator])) {
$operator = $operatorMap[$operator];
} else {
throw new InvalidParamException("Unsupported operator '{$operator}'");
}
}
return [$column => [$operator => $value]];
}
Composes log/profile token.
protected string composeLogToken ( $command, $arguments = [] ) | ||
$command | string |
Command name |
$arguments | array |
Command arguments. |
return | string |
Token. |
---|
protected function composeLogToken($command, $arguments = [])
{
$parts = [];
foreach ($arguments as $argument) {
$parts[] = is_scalar($argument) ? $argument : $this->encodeLogData($argument);
}
return $this->getFullName() . '.' . $command . '(' . implode(', ', $parts) . ')';
}
Creates an index on the collection and the specified fields.
public boolean createIndex ( $columns, $options = [] ) | ||
$columns | array|string |
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:
|
$options | array |
List of options in format: optionName => optionValue. |
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function createIndex($columns, $options = [])
{
$columns = (array)$columns;
$keys = $this->normalizeIndexKeys($columns);
$token = $this->composeLogToken('createIndex', [$keys, $options]);
$options = array_merge(['w' => 1], $options);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
if (method_exists($this->mongoCollection, 'createIndex')) {
$result = $this->mongoCollection->createIndex($keys, $options);
} else {
$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);
}
}
Returns a list of distinct values for the given column across a collection.
public array|boolean distinct ( $column, $condition = [] ) | ||
$column | string |
Column to use. |
$condition | array |
Query parameters. |
return | array|boolean |
Array of distinct values, or "false" on failure. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function distinct($column, $condition = [])
{
$condition = $this->buildCondition($condition);
$token = $this->composeLogToken('distinct', [$column, $condition]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
// See https://bugs.php.net/bug.php?id=68858
if (empty($condition)) {
$result = $this->mongoCollection->distinct($column);
} else {
$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);
}
}
Drops this collection.
public boolean drop ( ) | ||
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function drop()
{
$token = $this->composeLogToken('drop');
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);
}
}
Drops all indexes for this collection.
public integer dropAllIndexes ( ) | ||
return | integer |
Count of dropped indexes. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function dropAllIndexes()
{
$token = $this->composeLogToken('dropIndexes');
Yii::info($token, __METHOD__);
try {
$result = $this->mongoCollection->deleteIndexes();
$this->tryResultError($result);
return $result['nIndexesWas'];
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}
Drop indexes for specified column(s).
public boolean dropIndex ( $columns ) | ||
$columns | string|array |
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. Use value 'text' to specify text index. 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:
|
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function dropIndex($columns)
{
$columns = (array)$columns;
$keys = $this->normalizeIndexKeys($columns);
$token = $this->composeLogToken('dropIndex', [$keys]);
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);
}
}
Encodes complex log data into JSON format string.
protected string encodeLogData ( $data ) | ||
$data | mixed |
Raw data. |
return | string |
Encoded data string. |
---|
protected function encodeLogData($data)
{
return json_encode($this->processLogData($data));
}
Converts given value into MongoId instance.
If array given, each element of it will be processed.
protected array|\MongoId ensureMongoId ( $rawId ) | ||
$rawId | mixed |
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;
}
}
try {
$mongoId = new \MongoId($rawId);
} catch (\MongoException $e) {
// invalid id format
$mongoId = $rawId;
}
return $mongoId;
}
Returns a cursor for the search results.
In order to perform "find" queries use yii\mongodb\Query class.
See also yii\mongodb\Query.
public \MongoCursor find ( $condition = [], $fields = [] ) | ||
$condition | array |
Query condition |
$fields | array |
Fields to be selected |
return | \MongoCursor |
Cursor for the search results |
---|
public function find($condition = [], $fields = [])
{
return $this->mongoCollection->find($this->buildCondition($condition), $fields);
}
Updates a document and returns it.
See also http://www.php.net/manual/en/mongocollection.findandmodify.php.
public array|null findAndModify ( $condition, $update, $fields = [], $options = [] ) | ||
$condition | array |
Query condition |
$update | array |
Update criteria |
$fields | array |
Fields to be returned |
$options | array |
List of options in format: optionName => optionValue. |
return | array|null |
The original document, or the modified document when $options['new'] is set. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
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);
}
}
Returns a single document.
See also http://www.php.net/manual/en/mongocollection.findone.php.
public array|null findOne ( $condition = [], $fields = [] ) | ||
$condition | array |
Query condition |
$fields | array |
Fields to be selected |
return | array|null |
The single document. Null is returned if the query results in nothing. |
---|
public function findOne($condition = [], $fields = [])
{
return $this->mongoCollection->findOne($this->buildCondition($condition), $fields);
}
Performs full text search.
public array fullTextSearch ( $search, $condition = [], $fields = [], $options = [] ) | ||
$search | string |
String of terms that MongoDB parses and uses to query the text index. |
$condition | array |
Criteria for filtering a results list. |
$fields | array |
List of fields to be returned in result. |
$options | array |
Additional optional parameters to the mapReduce command. Valid options include:
|
return | array |
The highest scoring documents, in descending order by score. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function fullTextSearch($search, $condition = [], $fields = [], $options = [])
{
$command = [
'search' => $search
];
if (!empty($condition)) {
$command['filter'] = $this->buildCondition($condition);
}
if (!empty($fields)) {
$command['project'] = $fields;
}
if (!empty($options)) {
$command = array_merge($command, $options);
}
$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);
}
}
public string getFullName ( ) | ||
return | string |
Full name of this collection, including database name. |
---|
public function getFullName()
{
return $this->mongoCollection->__toString();
}
public array getLastError ( ) | ||
return | array |
Last error information. |
---|
public function getLastError()
{
return $this->mongoCollection->db->lastError();
}
public string getName ( ) | ||
return | string |
Name of this collection. |
---|
public function getName()
{
return $this->mongoCollection->getName();
}
Performs aggregation using Mongo "group" command.
See also http://docs.mongodb.org/manual/reference/command/group/.
public array group ( $keys, $initial, $reduce, $options = [] ) | ||
$keys | mixed |
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. |
$initial | array |
Initial value of the aggregation counter object. |
$reduce | \MongoCode|string |
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. |
$options | array |
Optional parameters to the group command. Valid options include:
|
return | array |
The result of the aggregation. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function group($keys, $initial, $reduce, $options = [])
{
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]);
Yii::info($token, __METHOD__);
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);
}
}
Inserts new data into collection.
public \MongoId insert ( $data, $options = [] ) | ||
$data | array|object |
Data to be inserted. |
$options | array |
List of options in format: optionName => optionValue. |
return | \MongoId |
New record id instance. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function insert($data, $options = [])
{
$token = $this->composeLogToken('insert', [$data]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$options = array_merge(['w' => 1], $options);
$this->tryResultError($this->mongoCollection->insert($data, $options));
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);
}
}
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. 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();
public string|array mapReduce ( $map, $reduce, $out, $condition = [], $options = [] ) | ||
$map | \MongoCode|string |
Function, which emits map data from collection. Argument will be automatically cast to \MongoCode. |
$reduce | \MongoCode|string |
Function that takes two arguments (the map key and the map values) and does the aggregation. Argument will be automatically cast to \MongoCode. |
$out | string|array |
Output collection name. It could be a string for simple output ('outputCollection'), or an array for parametrized output (['merge' => 'outputCollection']). You can pass ['inline' => true] to fetch the result at once without temporary collection usage. |
$condition | array |
Criteria for including a document in the aggregation. |
$options | array |
Additional optional parameters to the mapReduce command. Valid options include:
|
return | string|array |
The map reduce output collection name or output results. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function mapReduce($map, $reduce, $out, $condition = [], $options = [])
{
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);
}
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);
}
$token = $this->composeLogToken('mapReduce', [$map, $reduce, $out]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$command = array_merge(['mapReduce' => $this->getName()], $command);
$result = $this->mongoCollection->db->command($command);
$this->tryResultError($result);
Yii::endProfile($token, __METHOD__);
return array_key_exists('results', $result) ? $result['results'] : $result['result'];
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}
Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword.
protected string normalizeConditionKeyword ( $key ) | ||
$key | string |
Raw condition key. |
return | string |
Actual key. |
---|
protected function normalizeConditionKeyword($key)
{
static $map = [
'AND' => '$and',
'OR' => '$or',
'IN' => '$in',
'NOT IN' => '$nin',
];
$matchKey = strtoupper($key);
if (array_key_exists($matchKey, $map)) {
return $map[$matchKey];
} else {
return $key;
}
}
Compose index keys from given columns/keys list.
protected array normalizeIndexKeys ( $columns ) | ||
$columns | array |
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;
}
Pre-processes the log data before sending it to json_encode()
.
protected mixed processLogData ( $data ) | ||
$data | mixed |
Raw data. |
return | mixed |
The processed data. |
---|
protected function processLogData($data)
{
if (is_object($data)) {
if ($data instanceof \MongoId ||
$data instanceof \MongoRegex ||
$data instanceof \MongoDate ||
$data instanceof \MongoInt32 ||
$data instanceof \MongoInt64 ||
$data instanceof \MongoTimestamp
) {
$data = get_class($data) . '(' . $data->__toString() . ')';
} elseif ($data instanceof \MongoCode) {
$data = 'MongoCode( ' . $data->__toString() . ' )';
} elseif ($data instanceof \MongoBinData) {
$data = 'MongoBinData(...)';
} elseif ($data instanceof \MongoDBRef) {
$data = 'MongoDBRef(...)';
} elseif ($data instanceof \MongoMinKey || $data instanceof \MongoMaxKey) {
$data = get_class($data);
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$data[$key] = $this->processLogData($value);
}
}
}
return $data;
}
Removes data from the collection.
See also http://www.php.net/manual/en/mongocollection.remove.php.
public integer|boolean remove ( $condition = [], $options = [] ) | ||
$condition | array |
Description of records to remove. |
$options | array |
List of options in format: optionName => optionValue. |
return | integer|boolean |
Number of updated documents or whether operation was successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function remove($condition = [], $options = [])
{
$condition = $this->buildCondition($condition);
$options = array_merge(['w' => 1, 'justOne' => false], $options);
$token = $this->composeLogToken('remove', [$condition, $options]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$result = $this->mongoCollection->remove($condition, $options);
$this->tryResultError($result);
Yii::endProfile($token, __METHOD__);
if (is_array($result) && array_key_exists('n', $result)) {
return $result['n'];
} else {
return true;
}
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}
Update the existing database data, otherwise insert this data
public \MongoId save ( $data, $options = [] ) | ||
$data | array|object |
Data to be updated/inserted. |
$options | array |
List of options in format: optionName => optionValue. |
return | \MongoId |
Updated/new record id instance. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function save($data, $options = [])
{
$token = $this->composeLogToken('save', [$data]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$options = array_merge(['w' => 1], $options);
$this->tryResultError($this->mongoCollection->save($data, $options));
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);
}
}
Throws an exception if there was an error on the last operation.
protected void tryLastError ( ) | ||
throws | yii\mongodb\Exception |
if an error occurred. |
---|
protected function tryLastError()
{
$this->tryResultError($this->getLastError());
}
Checks if command execution result ended with an error.
protected void tryResultError ( $result ) | ||
$result | mixed |
Raw command execution result. |
throws | yii\mongodb\Exception |
if an error occurred. |
---|
protected function tryResultError($result)
{
if (is_array($result)) {
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);
}
} elseif (!$result) {
throw new Exception('Unknown error, use "w=1" option to enable error tracking');
}
}
Updates the rows, which matches given criteria by given data.
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.
public integer|boolean update ( $condition, $newData, $options = [] ) | ||
$condition | array |
Description of the objects to update. |
$newData | array |
The object with which to update the matching records. |
$options | array |
List of options in format: optionName => optionValue. |
return | integer|boolean |
Number of updated documents or whether operation was successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function update($condition, $newData, $options = [])
{
$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]);
Yii::info($token, __METHOD__);
try {
Yii::beginProfile($token, __METHOD__);
$result = $this->mongoCollection->update($condition, $newData, $options);
$this->tryResultError($result);
Yii::endProfile($token, __METHOD__);
if (is_array($result) && array_key_exists('n', $result)) {
return $result['n'];
} else {
return true;
}
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}