Class yii\mongodb\Collection

Inheritanceyii\mongodb\Collection » yii\base\Object
Subclassesyii\mongodb\file\Collection
Available since version2.0

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

Hide inherited properties

PropertyTypeDescriptionDefined By
$mongoCollection \MongoCollection Mongo collection instance. yii\mongodb\Collection

Public Methods

Hide inherited methods

MethodDescriptionDefined 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

Hide inherited methods

MethodDescriptionDefined 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 \yii\mongodb\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

$mongoCollection public property

Mongo collection instance.

public \MongoCollection $mongoCollection null

Method Details

aggregate() public method

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.

batchInsert() public method

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.

buildAndCondition() public method

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.

buildBetweenCondition() public method

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.

buildCondition() public method

Parses the condition specification and generates the corresponding Mongo condition.

public array buildCondition ( $condition )
$condition array

The condition specification. Please refer to yii\mongodb\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

buildHashCondition() public method

Creates a condition based on column-value pairs.

public array buildHashCondition ( $condition )
$condition array

The condition specification.

return array

The generated Mongo condition.

buildInCondition() public method

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.

buildLikeCondition() public method

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.

buildNotCondition() public method

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.

buildOrCondition() public method

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.

buildRegexCondition() public method

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.

buildSimpleCondition() public method

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.

composeLogToken() protected method

Composes log/profile token.

protected string composeLogToken ( $command, $arguments = [] )
$command string

Command name

$arguments array

Command arguments.

return string

Token.

createIndex() public method

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.

distinct() public method

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.

drop() public method

Drops this collection.

public boolean drop ( )
return boolean

Whether the operation successful.

throws yii\mongodb\Exception

on failure.

dropAllIndexes() public method

Drops all indexes for this collection.

public integer dropAllIndexes ( )
return integer

Count of dropped indexes.

throws yii\mongodb\Exception

on failure.

dropIndex() public method

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.

encodeLogData() protected method

Encodes complex log data into JSON format string.

protected string encodeLogData ( $data )
$data mixed

Raw data.

return string

Encoded data string.

ensureMongoId() protected method

Converts given value into \yii\mongodb\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).

find() public method

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

findAndModify() public method

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.

findOne() public method

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.

fullTextSearch() public method

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.

getFullName() public method

public string getFullName ( )
return string

Full name of this collection, including database name.

getLastError() public method

public array getLastError ( )
return array

Last error information.

getName() public method

public string getName ( )
return string

Name of this collection.

group() public method

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.

insert() public method

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.

mapReduce() public method

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.

normalizeConditionKeyword() protected method

Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword.

protected string normalizeConditionKeyword ( $key )
$key string

Raw condition key.

return string

Actual key.

normalizeIndexKeys() protected method

Compose index keys from given columns/keys list.

protected array normalizeIndexKeys ( $columns )
$columns array

Raw columns/keys list.

return array

Normalizes index keys array.

processLogData() protected method

Pre-processes the log data before sending it to json_encode().

protected mixed processLogData ( $data )
$data mixed

Raw data.

return mixed

The processed data.

remove() public method

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.

save() public method

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.

tryLastError() protected method

Throws an exception if there was an error on the last operation.

protected void tryLastError ( )
throws yii\mongodb\Exception

if an error occurred.

tryResultError() protected method

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.

update() public method

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.