Class yii\mongodb\Collection
Inheritance | yii\mongodb\Collection » yii\base\BaseObject |
---|---|
Subclasses | yii\mongodb\file\Collection |
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-mongodb/blob/master/src/Collection.php |
Collection represents the Mongo collection information.
A collection object is usually created by calling yii\mongodb\Database::getCollection() or yii\mongodb\Connection::getCollection().
Collection provides the basic interface for the Mongo queries, mostly: insert, update, delete operations. For example:
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
Collection also provides shortcut for yii\mongodb\Command methods, such as group(), mapReduce() and so on.
To perform "find" queries, please use yii\mongodb\Query instead.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$database | yii\mongodb\Database | MongoDB database instance. | yii\mongodb\Collection |
$fullName | string | Full name of this collection, including database name. | yii\mongodb\Collection |
$name | string | Name of this collection. | yii\mongodb\Collection |
Public Methods
Method | Description | Defined By |
---|---|---|
aggregate() | Performs aggregation using Mongo Aggregation Framework. | yii\mongodb\Collection |
batchInsert() | Inserts several new rows into collection. | yii\mongodb\Collection |
count() | Counts records in this collection. | yii\mongodb\Collection |
createIndex() | Creates an index on the collection and the specified fields. | yii\mongodb\Collection |
createIndexes() | Creates several indexes at once. | yii\mongodb\Collection |
distinct() | Returns a list of distinct values for the given column across a collection. | yii\mongodb\Collection |
documentExists() | Returns if a document exists. | 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 |
dropIndexes() | Drops collection indexes by name. | 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 |
getFullName() | yii\mongodb\Collection | |
group() | Performs aggregation using Mongo "group" command. | yii\mongodb\Collection |
insert() | Inserts new data into collection. | yii\mongodb\Collection |
listIndexes() | Returns the list of defined indexes. | yii\mongodb\Collection |
mapReduce() | Performs aggregation using MongoDB "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 |
Property Details
Full name of this collection, including database name.
Method Details
Performs aggregation using Mongo Aggregation Framework.
In case 'cursor' option is specified \MongoDB\Driver\Cursor instance is returned, otherwise - an array of aggregation results.
public array|\MongoDB\Driver\Cursor aggregate ( $pipelines, $options = [], $execOptions = [] ) | ||
$pipelines | array |
List of pipeline operators. |
$options | array |
Optional parameters. |
$execOptions | array |
{@see \yii\mongodb\Command::aggregate()} |
return | array|\MongoDB\Driver\Cursor |
The result of the aggregation. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function aggregate($pipelines, $options = [], $execOptions = [])
{
return $this->database->createCommand()->aggregate($this->name, $pipelines, $options, $execOptions);
}
Inserts several new rows into collection.
public array batchInsert ( $rows, $options = [], $execOptions = [] ) | ||
$rows | array |
Array of arrays or objects to be inserted. |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::batchInsert()} |
return | array |
Inserted data, each row will have "_id" key assigned to it. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function batchInsert($rows, $options = [], $execOptions = [])
{
$insertedIds = $this->database->createCommand()->batchInsert($this->name, $rows, $options, $execOptions);
foreach ($rows as $key => $row) {
$rows[$key]['_id'] = $insertedIds[$key];
}
return $rows;
}
Counts records in this collection.
public integer count ( $condition = [], $options = [], $execOptions = [] ) | ||
$condition | array |
Query condition |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::count()} |
return | integer |
Records count. |
---|
public function count($condition = [], $options = [], $execOptions = [])
{
return $this->database->createCommand()->count($this->name, $condition, $options, $execOptions);
}
Creates an index on the collection and the specified fields.
public boolean createIndex ( $columns, $options = [], $execOptions = [] ) | ||
$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. |
$execOptions | array |
{@see \yii\mongodb\Command::createIndexes()} |
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function createIndex($columns, $options = [], $execOptions = [])
{
$index = array_merge(['key' => $columns], $options);
return $this->database->createCommand()->createIndexes($this->name, [$index], $execOptions);
}
Creates several indexes at once.
Example:
$collection = Yii::$app->mongo->getCollection('customer');
$collection->createIndexes([
[
'key' => ['name'],
],
[
'key' => [
'email' => 1,
'address' => -1,
],
'name' => 'my_index'
],
]);
public boolean createIndexes ( $indexes, $execOptions = [] ) | ||
$indexes | array[] |
Indexes specification. Each specification should be an array in format: optionName => value The main options are:
See [[https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types]] for the full list of options. |
$execOptions | array |
{@see \yii\mongodb\Command::createIndexes()} |
return | boolean |
Whether operation was successful. |
---|
public function createIndexes($indexes, $execOptions = [])
{
return $this->database->createCommand()->createIndexes($this->name, $indexes, $execOptions);
}
Returns a list of distinct values for the given column across a collection.
public array|boolean distinct ( $column, $condition = [], $options = [], $execOptions = [] ) | ||
$column | string |
Column to use. |
$condition | array |
Query parameters. |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::distinct()} |
return | array|boolean |
Array of distinct values, or "false" on failure. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function distinct($column, $condition = [], $options = [], $execOptions = [])
{
return $this->database->createCommand()->distinct($this->name, $column, $condition, $options, $execOptions);
}
Returns if a document exists.
public boolean documentExists ( $condition = [] ) | ||
$condition | array |
Query condition. |
public function documentExists($condition = [])
{
return static::findOne($condition, ['_id' => 1]) !== null;
}
Drops this collection.
public boolean drop ( $execOptions = [] ) | ||
$execOptions | array |
{@see \yii\mongodb\Command::dropCollection()} |
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function drop($execOptions = [])
{
return $this->database->dropCollection($this->name, $execOptions);
}
Drops all indexes for this collection.
public integer dropAllIndexes ( $execOptions = [] ) | ||
$execOptions | array |
{@see \yii\mongodb\Command::dropIndexes()} |
return | integer |
Count of dropped indexes. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function dropAllIndexes($execOptions = [])
{
$result = $this->database->createCommand()->dropIndexes($this->name, '*', $execOptions);
return isset($result['nIndexesWas']) ? $result['nIndexesWas'] : 0;
}
Drop indexes for specified column(s).
public boolean dropIndex ( $columns, $execOptions = [] ) | ||
$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:
|
$execOptions | array |
{@see \yii\mongodb\Command::dropIndexes()} |
return | boolean |
Whether the operation successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function dropIndex($columns, $execOptions = [])
{
$existingIndexes = $this->listIndexes();
$indexKey = $this->database->connection->getQueryBuilder()->buildSortFields($columns);
foreach ($existingIndexes as $index) {
if ($index['key'] == $indexKey) {
$this->database->createCommand()->dropIndexes($this->name, $index['name'], $execOptions);
return true;
}
}
// Index plugin usage such as 'text' may cause unpredictable index 'key' structure, thus index name should be used
$indexName = $this->database->connection->getQueryBuilder()->generateIndexName($indexKey);
foreach ($existingIndexes as $index) {
if ($index['name'] === $indexName) {
$this->database->createCommand()->dropIndexes($this->name, $index['name'], $execOptions);
return true;
}
}
throw new Exception('Index to be dropped does not exist.');
}
Drops collection indexes by name.
public integer dropIndexes ( $indexes, $execOptions = [] ) | ||
$indexes | string |
Wildcard for name of the indexes to be dropped.
You can use |
$execOptions | array |
{@see \yii\mongodb\Command::dropIndexes()} |
return | integer |
Count of dropped indexes. |
---|
public function dropIndexes($indexes, $execOptions = [])
{
$result = $this->database->createCommand()->dropIndexes($this->name, $indexes, $execOptions);
return $result['nIndexesWas'];
}
Returns a cursor for the search results.
In order to perform "find" queries use yii\mongodb\Query class.
See also yii\mongodb\Query.
public \MongoDB\Driver\Cursor find ( $condition = [], $fields = [], $options = [], $execOptions = [] ) | ||
$condition | array |
Query condition |
$fields | array |
Fields to be selected |
$options | array |
Query options (available since 2.1). |
$execOptions | array |
{@see \yii\mongodb\Command::find()} |
return | \MongoDB\Driver\Cursor |
Cursor for the search results |
---|
public function find($condition = [], $fields = [], $options = [], $execOptions = [])
{
if (!empty($fields)) {
$options['projection'] = $fields;
}
return $this->database->createCommand()->find($this->name, $condition, $options, $execOptions);
}
Updates a document and returns it.
public array|null findAndModify ( $condition, $update, $options = [], $execOptions = [] ) | ||
$condition | array |
Query condition |
$update | array |
Update criteria |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::findAndModify()} |
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, $options = [], $execOptions = [])
{
return $this->database->createCommand()->findAndModify($this->name, $condition, $update, $options, $execOptions);
}
Returns a single document.
public array|null findOne ( $condition = [], $fields = [], $options = [], $execOptions = [] ) | ||
$condition | array |
Query condition |
$fields | array |
Fields to be selected |
$options | array |
Query options (available since 2.1). |
$execOptions | array |
{@see \yii\mongodb\find()} |
return | array|null |
The single document. Null is returned if the query results in nothing. |
---|
public function findOne($condition = [], $fields = [], $options = [], $execOptions = [])
{
$options['limit'] = 1;
$cursor = $this->find($condition, $fields, $options, $execOptions);
$rows = $cursor->toArray();
return empty($rows) ? null : current($rows);
}
public string getFullName ( ) | ||
return | string |
Full name of this collection, including database name. |
---|
public function getFullName()
{
return $this->database->name . '.' . $this->name;
}
Performs aggregation using Mongo "group" command.
public array group ( $keys, $initial, $reduce, $options = [], $execOptions = [] ) | ||
$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 \MongoDB\BSON\Javascript 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 | \MongoDB\BSON\Javascript|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 \MongoDB\BSON\Javascript. |
$options | array |
Optional parameters to the group command. Valid options include:
|
$execOptions | array |
{@see \yii\mongodb\Command::group()} |
return | array |
The result of the aggregation. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function group($keys, $initial, $reduce, $options = [], $execOptions = [])
{
return $this->database->createCommand()->group($this->name, $keys, $initial, $reduce, $options, $execOptions);
}
Inserts new data into collection.
public \MongoDB\BSON\ObjectID insert ( $data, $options = [], $execOptions = [] ) | ||
$data | array|object |
Data to be inserted. |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::insert()} |
return | \MongoDB\BSON\ObjectID |
New record ID instance. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function insert($data, $options = [], $execOptions = [])
{
return $this->database->createCommand()->insert($this->name, $data, $options, $execOptions);
}
Returns the list of defined indexes.
public array listIndexes ( $options = [], $execOptions = [] ) | ||
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::listIndexes()} |
return | array |
List of indexes info. |
---|
public function listIndexes($options = [], $execOptions = [])
{
return $this->database->createCommand()->listIndexes($this->name, $options, $execOptions);
}
Performs aggregation using MongoDB "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 = [], $execOptions = [] ) | ||
$map | \MongoDB\BSON\Javascript|string |
Function, which emits map data from collection. Argument will be automatically cast to \MongoDB\BSON\Javascript. |
$reduce | \MongoDB\BSON\Javascript|string |
Function that takes two arguments (the map key and the map values) and does the aggregation. Argument will be automatically cast to \MongoDB\BSON\Javascript. |
$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:
|
$execOptions | array |
{@see \yii\mongodb\Command::mapReduce()} |
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 = [], $execOptions = [])
{
return $this->database->createCommand()->mapReduce($this->name, $map, $reduce, $out, $condition, $options, $execOptions);
}
Removes data from the collection.
public integer|boolean remove ( $condition = [], $options = [], $execOptions = [] ) | ||
$condition | array |
Description of records to remove. |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::delete()} |
return | integer|boolean |
Number of updated documents or whether operation was successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function remove($condition = [], $options = [], $execOptions = [])
{
$options = array_merge(['limit' => 0], $options);
$writeResult = $this->database->createCommand()->delete($this->name, $condition, $options, $execOptions);
return $writeResult->getDeletedCount();
}
Update the existing database data, otherwise insert this data
public \MongoDB\BSON\ObjectID save ( $data, $options = [], $execOptions = [] ) | ||
$data | array|object |
Data to be updated/inserted. |
$options | array |
List of options in format: optionName => optionValue. |
$execOptions | array |
{@see \yii\mongodb\Command::insert()} |
return | \MongoDB\BSON\ObjectID |
Updated/new record id instance. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function save($data, $options = [], $execOptions = [])
{
if (empty($data['_id'])) {
return $this->insert($data, $options, $execOptions);
}
$id = $data['_id'];
unset($data['_id']);
$this->update(['_id' => $id], ['$set' => $data], ['upsert' => true], $execOptions);
return is_object($id) ? $id : new ObjectID($id);
}
Updates the rows, which matches given criteria by given data.
Note: for "multi" 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 = [], $execOptions = [] ) | ||
$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. |
$execOptions | array |
{@see \yii\mongodb\Command::update()} |
return | integer|boolean |
Number of updated documents or whether operation was successful. |
---|---|---|
throws | yii\mongodb\Exception |
on failure. |
public function update($condition, $newData, $options = [], $execOptions = [])
{
$writeResult = $this->database->createCommand()->update($this->name, $condition, $newData, $options, $execOptions);
return $writeResult->getModifiedCount() + $writeResult->getUpsertedCount();
}