Class yii\mongodb\Collection
Inheritance | yii\mongodb\Collection » yii\base\Object |
---|---|
Subclasses | yii\mongodb\file\Collection |
Available since version | 2.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
Property | Type | Description | Defined By |
---|---|---|---|
$mongoCollection | \MongoCollection | Mongo collection instance. | 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 \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
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. |
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. |
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. |
---|
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. |
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 |
Creates a condition based on column-value pairs.
public array buildHashCondition ( $condition ) | ||
$condition | array | The condition specification. |
return | array | The generated Mongo condition. |
---|
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. |
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. |
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. |
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. |
---|
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. |
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. |
Composes log/profile token.
protected string composeLogToken ( $command, $arguments = [] ) | ||
$command | string | Command name |
$arguments | array | Command arguments. |
return | string | Token. |
---|
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. |
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. |
Drops this collection.
public boolean drop ( ) | ||
return | boolean | Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception | on failure. |
Drops all indexes for this collection.
public integer dropAllIndexes ( ) | ||
return | integer | Count of dropped indexes. |
---|---|---|
throws | yii\mongodb\Exception | on failure. |
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. |
Encodes complex log data into JSON format string.
protected string encodeLogData ( $data ) | ||
$data | mixed | Raw data. |
return | string | Encoded data string. |
---|
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). |
---|
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 |
---|
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. |
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. |
---|
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 string getFullName ( ) | ||
return | string | Full name of this collection, including database name. |
---|
public array getLastError ( ) | ||
return | array | Last error information. |
---|
public string getName ( ) | ||
return | string | Name of this collection. |
---|
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. |
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. |
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. |
Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword.
protected string normalizeConditionKeyword ( $key ) | ||
$key | string | Raw condition key. |
return | string | Actual 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. |
---|
Pre-processes the log data before sending it to json_encode()
.
protected mixed processLogData ( $data ) | ||
$data | mixed | Raw data. |
return | mixed | The processed 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. |
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. |
Throws an exception if there was an error on the last operation.
protected void tryLastError ( ) | ||
throws | yii\mongodb\Exception | if an error occurred. |
---|
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. |
---|
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. |