Class yii\mongodb\Collection

Inheritanceyii\mongodb\Collection » yii\base\BaseObject
Implementsyii\base\Configurable
Subclassesyii\mongodb\file\Collection
Available since version2.0
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/Collection.php

Collection represents the Mongo collection information.

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

Collection provides the basic interface for the Mongo queries, mostly: insert, update, delete operations. For example:

$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);

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

Hide inherited properties

PropertyTypeDescriptionDefined By
$database yii\mongodb\Database MongoDB database instance. yii\mongodb\Collection
$fullName string Full name of this collection, including database name. This property is read-only. yii\mongodb\Collection
$name string Name of this collection. yii\mongodb\Collection

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
aggregate() Performs aggregation using Mongo Aggregation Framework. yii\mongodb\Collection
batchInsert() Inserts several new rows into collection. yii\mongodb\Collection
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
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
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
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

$database public property

MongoDB database instance.

$fullName public property

Full name of this collection, including database name. This property is read-only.

public string $fullName null
$name public property

Name of this collection.

public string $name null

Method Details

aggregate() public method

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 = [] )
$pipelines array

List of pipeline operators.

$options array

Optional parameters.

return array|\MongoDB\Driver\Cursor

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.

count() public method (available since version 2.1)

Counts records in this collection.

public integer count ( $condition = [], $options = [] )
$condition array

Query condition

$options array

List of options in format: optionName => optionValue.

return integer

Records count.

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.

createIndexes() public method (available since version 2.1)

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 )
$indexes array[]

Indexes specification. Each specification should be an array in format: optionName => value The main options are:

  • keys: array, column names with sort order, to be indexed. This option is mandatory.
  • unique: bool, whether to create unique index.
  • name: string, the name of the index, if not set it will be generated automatically.
  • background: bool, whether to bind index in the background.
  • sparse: bool, whether index should reference only documents with the specified field.

See [[https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types]] for the full list of options.

return boolean

Whether operation was successful.

distinct() public method

Returns a list of distinct values for the given column across a collection.

public array|boolean distinct ( $column, $condition = [], $options = [] )
$column string

Column to use.

$condition array

Query parameters.

$options array

List of options in format: optionName => optionValue.

return array|boolean

Array of distinct values, or "false" on failure.

throws yii\mongodb\Exception

on failure.

documentExists() public method (available since version 2.0.39)

Returns if a document exists.

public boolean documentExists ( $condition = [] )
$condition array

Query condition.

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.

dropIndexes() public method

Drops collection indexes by name.

public integer dropIndexes ( $indexes )
$indexes string

Wildcard for name of the indexes to be dropped. You can use * to drop all indexes.

return integer

Count of dropped indexes.

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 \MongoDB\Driver\Cursor find ( $condition = [], $fields = [], $options = [] )
$condition array

Query condition

$fields array

Fields to be selected

$options array

Query options (available since 2.1).

return \MongoDB\Driver\Cursor

Cursor for the search results

findAndModify() public method

Updates a document and returns it.

public array|null findAndModify ( $condition, $update, $options = [] )
$condition array

Query condition

$update array

Update criteria

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

public array|null findOne ( $condition = [], $fields = [], $options = [] )
$condition array

Query condition

$fields array

Fields to be selected

$options array

Query options (available since 2.1).

return array|null

The single document. Null is returned if the query results in nothing.

getFullName() public method

public string getFullName ( )
return string

Full name of this collection, including database name.

group() public method

Performs aggregation using Mongo "group" command.

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 \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:

  • 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 \MongoDB\BSON\ObjectID insert ( $data, $options = [] )
$data array|object

Data to be inserted.

$options array

List of options in format: optionName => optionValue.

return \MongoDB\BSON\ObjectID

New record ID instance.

throws yii\mongodb\Exception

on failure.

listIndexes() public method (available since version 2.1)

Returns the list of defined indexes.

public array listIndexes ( $options = [] )
$options array

List of options in format: optionName => optionValue.

return array

List of indexes info.

mapReduce() public method

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 = [] )
$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:

  • sort: array, key to sort the input documents. The sort key must be in an existing index for this collection.
  • limit: int, the maximum number of documents to return in the collection.
  • finalize: \MongoDB\BSON\Javascript|string, 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: bool, specifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions.
  • verbose: bool, 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.

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.

save() public method

Update the existing database data, otherwise insert this data

public \MongoDB\BSON\ObjectID save ( $data, $options = [] )
$data array|object

Data to be updated/inserted.

$options array

List of options in format: optionName => optionValue.

return \MongoDB\BSON\ObjectID

Updated/new record id instance.

throws yii\mongodb\Exception

on failure.

update() public method

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 = [] )
$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.