Class yii\mongodb\file\Collection

Inheritanceyii\mongodb\file\Collection » yii\mongodb\Collection » yii\base\BaseObject
Implementsyii\base\Configurable
Available since 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
$database yii\mongodb\Database MongoDB database instance. yii\mongodb\file\Collection
$fileCollection yii\mongodb\Collection Mongo collection instance. yii\mongodb\file\Collection
$fullName string Full name of this collection, including database name. yii\mongodb\Collection
$name string Name of this collection. yii\mongodb\Collection
$prefix string Prefix of this file collection. yii\mongodb\file\Collection

Public Methods

Hide inherited methods

Method Description Defined 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
createDownload() Creates download command. yii\mongodb\file\Collection
createIndex() Creates an index on the collection and the specified fields. yii\mongodb\Collection
createIndexes() Creates several indexes at once. yii\mongodb\Collection
createUpload() Creates upload command. yii\mongodb\file\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
documentExists() Returns if a document exists. yii\mongodb\Collection
drop() Drops this collection. yii\mongodb\file\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
ensureIndexes() Makes sure that indexes, which are crucial for the file processing, exist at this collection and $chunkCollection. yii\mongodb\file\Collection
find() Returns a cursor for the search results. yii\mongodb\file\Collection
findAndModify() Updates a document and returns it. yii\mongodb\Collection
findOne() Returns a single document. yii\mongodb\Collection
get() Retrieves the file with given _id. yii\mongodb\file\Collection
getChunkCollection() Returns the MongoDB collection for the file chunks. yii\mongodb\file\Collection
getFileCollection() Returns the MongoDB collection for the files. yii\mongodb\file\Collection
getFullName() yii\mongodb\Collection
getPrefix() yii\mongodb\file\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
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
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\file\Collection
save() Update the existing database data, otherwise insert this data yii\mongodb\Collection
setPrefix() yii\mongodb\file\Collection
update() Updates the rows, which matches given criteria by given data. yii\mongodb\Collection

Property Details

Hide inherited properties

$chunkCollection public property

Mongo collection instance.

$database public property

MongoDB database instance.

$fileCollection public property

Mongo collection instance.

$prefix public property

Prefix of this file collection.

public string $prefix null

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
aggregate() public method

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

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

            
batchInsert() public method

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

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

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
count() public method (available since version 2.1)

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

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

            
createDownload() public method (available since version 2.1)

Creates download command.

public yii\mongodb\file\Download createDownload ( $document )
$document array|\MongoDB\BSON\ObjectID

File document ot be downloaded.

return yii\mongodb\file\Download

File download instance.

                public function createDownload($document)
{
    return new Download([
        'collection' => $this,
        'document' => $document,
    ]);
}

            
createIndex() public method

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

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:

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

            
createIndexes() public method (available since version 2.1)

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

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:

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

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

            
createUpload() public method (available since version 2.1)

Creates upload command.

public yii\mongodb\file\Upload createUpload ( $options = [] )
$options array

Upload options.

return yii\mongodb\file\Upload

File upload instance.

                public function createUpload($options = [])
{
    $config = $options;
    $config['collection'] = $this;
    return new Upload($config);
}

            
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)
{
    $this->remove(['_id' => $id], ['limit' => 1]);
    return true;
}

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

            
documentExists() public method (available since version 2.0.39)

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

Returns if a document exists.

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

Query condition.

                public function documentExists($condition = [])
{
    return static::findOne($condition, ['_id' => 1]) !== null;
}

            
drop() public method

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 parent::drop($execOptions) && $this->database->dropCollection($this->getChunkCollection()->name,$execOptions);
}

            
dropAllIndexes() public method

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

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

            
dropIndex() public method

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

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:

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

            
dropIndexes() public method

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

Drops collection indexes by name.

public integer dropIndexes ( $indexes, $execOptions = [] )
$indexes string

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

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

            
ensureIndexes() public method

Makes sure that indexes, which are crucial for the file processing, exist at this collection and $chunkCollection.

The check result is cached per collection instance.

public $this ensureIndexes ( $force false )
$force boolean

Whether to ignore internal collection instance cache.

return $this

Self reference.

                public function ensureIndexes($force = false)
{
    if (!$force && $this->indexesEnsured) {
        return $this;
    }
    $this->ensureFileIndexes();
    $this->ensureChunkIndexes();
    $this->indexesEnsured = true;
    return $this;
}

            
find() public method

Returns a cursor for the search results.

In order to perform "find" queries use yii\mongodb\file\Query class.

public yii\mongodb\file\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 yii\mongodb\file\Cursor

Cursor for the search results

                public function find($condition = [], $fields = [], $options = [], $execOptions = [])
{
    return new Cursor($this, parent::find($condition, $fields, $options, $execOptions));
}

            
findAndModify() public method

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

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

            
findOne() public method

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

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

            
get() public method

Retrieves the file with given _id.

public yii\mongodb\file\Download|null get ( $id )
$id mixed

_id of the file to find.

return yii\mongodb\file\Download|null

Found file, or null if file does not exist

throws yii\mongodb\Exception

on failure.

                public function get($id)
{
    $document = $this->getFileCollection()->findOne(['_id' => $id]);
    return empty($document) ? null : $this->createDownload($document);
}

            
getChunkCollection() public method

Returns the MongoDB 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',
            'database' => $this->database,
            'name' => $this->getPrefix() . '.chunks'
        ]);
    }
    return $this->_chunkCollection;
}

            
getFileCollection() public method (available since version 2.1)

Returns the MongoDB collection for the files.

public yii\mongodb\Collection getFileCollection ( $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 getFileCollection($refresh = false)
{
    if ($refresh || !is_object($this->_fileCollection)) {
        $this->_fileCollection = Yii::createObject([
            'class' => 'yii\mongodb\Collection',
            'database' => $this->database,
            'name' => $this->name
        ]);
    }
    return $this->_fileCollection;
}

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

Full name of this collection, including database name.

                public function getFullName()
{
    return $this->database->name . '.' . $this->name;
}

            
getPrefix() public method

public string getPrefix ( )
return string

Prefix of this file collection.

                public function getPrefix()
{
    return $this->_prefix;
}

            
group() public method

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

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:

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

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Defined in: yii\base\BaseObject::init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
}

            
insert() public method

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

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

            
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 = [])
{
    $options['document'] = $metadata;
    $document = $this->createUpload($options)->addFile($filename)->complete();
    return $document['_id'];
}

            
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 = [])
{
    $options['document'] = $metadata;
    $document = $this->createUpload($options)->addContent($bytes)->complete();
    return $document['_id'];
}

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

$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 insertUploads($name, $metadata = [], $options = [])
{
    $uploadedFile = UploadedFile::getInstanceByName($name);
    if ($uploadedFile === null) {
        throw new Exception("Uploaded file '{$name}' does not exist.");
    }
    $options['filename'] = $uploadedFile->name;
    $options['document'] = $metadata;
    $document = $this->createUpload($options)->addFile($uploadedFile->tempName)->complete();
    return $document['_id'];
}

            
listIndexes() public method (available since version 2.1)

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

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

            
mapReduce() public method

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

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:

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

            
remove() public method

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 = [])
{
    $fileCollection = $this->getFileCollection();
    $chunkCollection = $this->getChunkCollection();
    if (empty($condition) && empty($options['limit'])) {
        // truncate :
        $deleteCount = $fileCollection->remove([], $options);
        $chunkCollection->remove([], $options);
        return $deleteCount;
    }
    $batchSize = 200;
    $options['batchSize'] = $batchSize;
    $cursor = $fileCollection->find($condition, ['_id'], $options, $execOptions);
    unset($options['limit']);
    $deleteCount = 0;
    $deleteCallback = function ($ids) use ($fileCollection, $chunkCollection, $options) {
        $chunkCollection->remove(['files_id' => ['$in' => $ids]], $options);
        return $fileCollection->remove(['_id' => ['$in' => $ids]], $options);
    };
    $ids = [];
    $idsCount = 0;
    foreach ($cursor as $row) {
        $ids[] = $row['_id'];
        $idsCount++;
        if ($idsCount >= $batchSize) {
            $deleteCount += $deleteCallback($ids);
            $ids = [];
            $idsCount = 0;
        }
    }
    if (!empty($ids)) {
        $deleteCount += $deleteCallback($ids);
    }
    return $deleteCount;
}

            
save() public method

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

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

            
setPrefix() public method

public void setPrefix ( $prefix )
$prefix string

Prefix of this file collection.

                public function setPrefix($prefix)
{
    $this->_prefix = $prefix;
    $this->name = $prefix . '.files';
}

            
update() public method

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

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