Class yii\mongodb\file\Collection

Inheritanceyii\mongodb\file\Collection » yii\mongodb\Collection » yii\base\Object
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/file/Collection.php

Collection represents the Mongo GridFS collection information.

A file collection object is usually created by calling yii\mongodb\Database::getFileCollection() or yii\mongodb\Connection::getFileCollection().

File collection inherits all interface from regular \yii\mongo\Collection, adding methods to store files.

Public Properties

Hide inherited properties

Property Type Description Defined By
$chunkCollection yii\mongodb\Collection Mongo collection instance. yii\mongodb\file\Collection
$fullName string Full name of this collection, including database name. yii\mongodb\Collection
$lastError array Last error information. yii\mongodb\Collection
$mongoCollection \MongoGridFS Mongo GridFS collection instance. yii\mongodb\file\Collection
$name string Name of this collection. yii\mongodb\Collection

Public Methods

Hide inherited 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
delete() Deletes the file with given _id. yii\mongodb\file\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
get() Retrieves the file with given _id. yii\mongodb\file\Collection
getChunkCollection() Returns the Mongo collection for the file chunks. yii\mongodb\file\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
insertFile() Creates new file in GridFS collection from given local filesystem file. yii\mongodb\file\Collection
insertFileContent() Creates new file in GridFS collection with specified content. yii\mongodb\file\Collection
insertUploads() Creates new file in GridFS collection from uploaded file. yii\mongodb\file\Collection
mapReduce() Performs aggregation using Mongo "map reduce" mechanism. yii\mongodb\Collection
remove() Removes data from the collection. yii\mongodb\file\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

Hide inherited 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

Hide inherited properties

$chunkCollection public property

Mongo collection instance. This property is read-only.

$mongoCollection public property

Mongo GridFS collection instance.

public \MongoGridFS $mongoCollection null

Method Details

Hide inherited methods

aggregate() public method

Defined in: yii\mongodb\Collection::aggregate()

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);
    }
}

            
batchInsert() public method

Defined in: yii\mongodb\Collection::batchInsert()

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);
    }
}

            
buildAndCondition() public method

Defined in: yii\mongodb\Collection::buildAndCondition()

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];
}

            
buildBetweenCondition() public method

Defined in: yii\mongodb\Collection::buildBetweenCondition()

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,
            ]
        ];
    }
}

            
buildCondition() public method

Defined in: yii\mongodb\Collection::buildCondition()

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);
    }
}

            
buildHashCondition() public method

Defined in: yii\mongodb\Collection::buildHashCondition()

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;
}

            
buildInCondition() public method

Defined in: yii\mongodb\Collection::buildInCondition()

Creates an Mongo condition with the IN operator.

public array buildInCondition ( $operator, $operands )
$operator string

The operator to use (e.g. IN or NOT IN)

$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;
}

            
buildLikeCondition() public method

Defined in: yii\mongodb\Collection::buildLikeCondition()

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];
}

            
buildNotCondition() public method

Defined in: yii\mongodb\Collection::buildNotCondition()

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;
}

            
buildOrCondition() public method

Defined in: yii\mongodb\Collection::buildOrCondition()

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];
}

            
buildRegexCondition() public method

Defined in: yii\mongodb\Collection::buildRegexCondition()

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];
}

            
buildSimpleCondition() public method

Defined in: yii\mongodb\Collection::buildSimpleCondition()

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 >, <=, and so on, can be used here.

$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]];
}

            
composeLogToken() protected method

Defined in: yii\mongodb\Collection::composeLogToken()

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) . ')';
}

            
createIndex() public method

Defined in: yii\mongodb\Collection::createIndex()

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:

[
    'name',
    'status' => -1,
]
$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);
    }
}

            
delete() public method

Deletes the file with given _id.

public boolean delete ( $id )
$id mixed

_id of the file to find.

return boolean

Whether the operation was successful.

throws yii\mongodb\Exception

on failure.

                public function delete($id)
{
    $token = 'Inserting file uploads into ' . $this->getFullName();
    Yii::info($token, __METHOD__);
    try {
        Yii::beginProfile($token, __METHOD__);
        $result = $this->mongoCollection->delete($id);
        $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);
    }
}

            
distinct() public method

Defined in: yii\mongodb\Collection::distinct()

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);
    }
}

            
drop() public method

Defined in: yii\mongodb\Collection::drop()

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);
    }
}

            
dropAllIndexes() public method

Defined in: yii\mongodb\Collection::dropAllIndexes()

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);
    }
}

            
dropIndex() public method

Defined in: yii\mongodb\Collection::dropIndex()

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:

[
    'name',
    'status' => -1,
    'description' => 'text',
]
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);
    }
}

            
encodeLogData() protected method

Defined in: yii\mongodb\Collection::encodeLogData()

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));
}

            
ensureMongoId() protected method

Defined in: yii\mongodb\Collection::ensureMongoId()

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;
}

            
find() public method

Defined in: yii\mongodb\Collection::find()

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);
}

            
findAndModify() public method
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);
    }
}

            
findOne() public method
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);
}

            
fullTextSearch() public method

Defined in: yii\mongodb\Collection::fullTextSearch()

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:

  • 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 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 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);
    }
}

            
get() public method

Retrieves the file with given _id.

public \MongoGridFSFile|null get ( $id )
$id mixed

_id of the file to find.

return \MongoGridFSFile|null

Found file, or null if file does not exist

throws yii\mongodb\Exception

on failure.

                public function get($id)
{
    $token = 'Inserting file uploads into ' . $this->getFullName();
    Yii::info($token, __METHOD__);
    try {
        Yii::beginProfile($token, __METHOD__);
        $result = $this->mongoCollection->get($id);
        Yii::endProfile($token, __METHOD__);
        return $result;
    } catch (\Exception $e) {
        Yii::endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
    }
}

            
getChunkCollection() public method

Returns the Mongo collection for the file chunks.

public yii\mongodb\Collection getChunkCollection ( $refresh false )
$refresh boolean

Whether to reload the collection instance even if it is found in the cache.

return yii\mongodb\Collection

Mongo collection instance.

                public function getChunkCollection($refresh = false)
{
    if ($refresh || !is_object($this->_chunkCollection)) {
        $this->_chunkCollection = Yii::createObject([
            'class' => 'yii\mongodb\Collection',
            'mongoCollection' => $this->mongoCollection->chunks
        ]);
    }
    return $this->_chunkCollection;
}

            
getFullName() public method
public string getFullName ( )
return string

Full name of this collection, including database name.

                public function getFullName()
{
    return $this->mongoCollection->__toString();
}

            
getLastError() public method
public array getLastError ( )
return array

Last error information.

                public function getLastError()
{
    return $this->mongoCollection->db->lastError();
}

            
getName() public method
public string getName ( )
return string

Name of this collection.

                public function getName()
{
    return $this->mongoCollection->getName();
}

            
group() public method

Defined in: yii\mongodb\Collection::group()

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:

  • 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.

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);
    }
}

            
insert() public method

Defined in: yii\mongodb\Collection::insert()

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);
    }
}

            
insertFile() public method

Creates new file in GridFS collection from given local filesystem file.

Additional attributes can be added file document using $metadata.

public mixed insertFile ( $filename, $metadata = [], $options = [] )
$filename string

Name of the file to store.

$metadata array

Other metadata fields to include in the file document.

$options array

List of options in format: optionName => optionValue

return mixed

The "_id" of the saved file document. This will be a generated \MongoId unless an "_id" was explicitly specified in the metadata.

throws yii\mongodb\Exception

on failure.

                public function insertFile($filename, $metadata = [], $options = [])
{
    $token = 'Inserting file into ' . $this->getFullName();
    Yii::info($token, __METHOD__);
    try {
        Yii::beginProfile($token, __METHOD__);
        $options = array_merge(['w' => 1], $options);
        $result = $this->mongoCollection->storeFile($filename, $metadata, $options);
        Yii::endProfile($token, __METHOD__);
        return $result;
    } catch (\Exception $e) {
        Yii::endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
    }
}

            
insertFileContent() public method

Creates new file in GridFS collection with specified content.

Additional attributes can be added file document using $metadata.

public mixed insertFileContent ( $bytes, $metadata = [], $options = [] )
$bytes string

String of bytes to store.

$metadata array

Other metadata fields to include in the file document.

$options array

List of options in format: optionName => optionValue

return mixed

The "_id" of the saved file document. This will be a generated \MongoId unless an "_id" was explicitly specified in the metadata.

throws yii\mongodb\Exception

on failure.

                public function insertFileContent($bytes, $metadata = [], $options = [])
{
    $token = 'Inserting file content into ' . $this->getFullName();
    Yii::info($token, __METHOD__);
    try {
        Yii::beginProfile($token, __METHOD__);
        $options = array_merge(['w' => 1], $options);
        $result = $this->mongoCollection->storeBytes($bytes, $metadata, $options);
        Yii::endProfile($token, __METHOD__);
        return $result;
    } catch (\Exception $e) {
        Yii::endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
    }
}

            
insertUploads() public method

Creates new file in GridFS collection from uploaded file.

Additional attributes can be added file document using $metadata.

public mixed insertUploads ( $name, $metadata = [] )
$name string

Name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form.

$metadata array

Other metadata fields to include in the file document.

return mixed

The "_id" of the saved file document. This will be a generated \MongoId unless an "_id" was explicitly specified in the metadata.

throws yii\mongodb\Exception

on failure.

                public function insertUploads($name, $metadata = [])
{
    $token = 'Inserting file uploads into ' . $this->getFullName();
    Yii::info($token, __METHOD__);
    try {
        Yii::beginProfile($token, __METHOD__);
        $result = $this->mongoCollection->storeUpload($name, $metadata);
        Yii::endProfile($token, __METHOD__);
        return $result;
    } catch (\Exception $e) {
        Yii::endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
    }
}

            
mapReduce() public method

Defined in: yii\mongodb\Collection::mapReduce()

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:

  • 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.
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);
    }
}

            
normalizeConditionKeyword() protected method

Defined in: yii\mongodb\Collection::normalizeConditionKeyword()

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;
    }
}

            
normalizeIndexKeys() protected method

Defined in: yii\mongodb\Collection::normalizeIndexKeys()

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;
}

            
processLogData() protected method

Defined in: yii\mongodb\Collection::processLogData()

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;
}

            
remove() public method

Removes data from the collection.

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 = [])
{
    $result = parent::remove($condition, $options);
    $this->tryLastError(); // MongoGridFS::remove will return even if the remove failed
    return $result;
}

            
save() public method

Defined in: yii\mongodb\Collection::save()

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);
    }
}

            
tryLastError() protected method

Defined in: yii\mongodb\Collection::tryLastError()

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());
}

            
tryResultError() protected method

Defined in: yii\mongodb\Collection::tryResultError()

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');
    }
}

            
update() public method

Defined in: yii\mongodb\Collection::update()

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);
    }
}