Class yii\mongodb\Command

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

Command represents MongoDB statement such as command or query.

A command object is usually created by calling yii\mongodb\Connection::createCommand() or yii\mongodb\Database::createCommand(). The statement it represents can be set via the $document property.

To execute a non-query command, such as 'listIndexes', 'count', 'distinct' and so on, call execute(). For example:

$result = Yii::$app->mongodb->createCommand(['listIndexes' => 'some_collection'])->execute();

To execute a 'find' command, which return cursor, call query(). For example:

$cursor = Yii::$app->mongodb->createCommand(['projection' => ['name' => true]])->query('some_collection');

To execute batch (bulk) operations, call executeBatch(). For example:

Yii::$app->mongodb->createCommand()
    ->addInsert(['name' => 'new'])
    ->addUpdate(['name' => 'existing'], ['name' => 'updated'])
    ->addDelete(['name' => 'old'])
    ->executeBatch('some_collection');

Public Properties

Hide inherited properties

Property Type Description Defined By
$databaseName string Name of the database that this command is associated with. yii\mongodb\Command
$db yii\mongodb\Connection The MongoDB connection that this command is associated with. yii\mongodb\Command
$document array Command document contents. yii\mongodb\Command
$globalExecOptions array Default options for executeCommand method of MongoDB\Driver\Manager. yii\mongodb\Command
$readConcern \MongoDB\Driver\ReadConcern|string Read concern to be used in this command. yii\mongodb\Command
$readPreference \MongoDB\Driver\ReadPreference Read preference. yii\mongodb\Command
$writeConcern \MongoDB\Driver\WriteConcern|null Write concern to be used in this command. yii\mongodb\Command

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
addDelete() Adds the delete operation to the batch command. yii\mongodb\Command
addInsert() Adds the insert operation to the batch command. yii\mongodb\Command
addUpdate() Adds the update operation to the batch command. yii\mongodb\Command
aggregate() Performs aggregation using MongoDB Aggregation Framework. yii\mongodb\Command
batchInsert() Inserts batch of new documents into collection. yii\mongodb\Command
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 specified collection. yii\mongodb\Command
createCollection() Creates new collection in database associated with this command.s yii\mongodb\Command
createIndexes() Creates indexes in the collection. yii\mongodb\Command
delete() Removes documents from the collection. yii\mongodb\Command
distinct() Returns a list of distinct values for the given column across a collection. yii\mongodb\Command
dropCollection() Drops specified collection. yii\mongodb\Command
dropDatabase() Drops database associated with this command. yii\mongodb\Command
dropIndexes() Drops collection indexes by name. yii\mongodb\Command
execute() Executes this command. yii\mongodb\Command
executeBatch() Execute commands batch (bulk). yii\mongodb\Command
explain() Return an explanation of the query, often useful for optimization and debugging. yii\mongodb\Command
find() Performs find query. yii\mongodb\Command
findAndModify() Updates a document and returns it. yii\mongodb\Command
group() Performs aggregation using MongoDB "group" command. yii\mongodb\Command
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 document into collection. yii\mongodb\Command
listCollections() Returns the list of available collections. yii\mongodb\Command
listDatabases() Returns the list of available databases. yii\mongodb\Command
listIndexes() Returns information about current collection indexes. yii\mongodb\Command
mapReduce() Performs MongoDB "map-reduce" command. yii\mongodb\Command
prepareManagerOptions() Preapare Concern and Preference options for easy use yii\mongodb\Command
query() Executes this command as a mongo query yii\mongodb\Command
update() Update existing documents in the collection. yii\mongodb\Command

Protected Methods

Hide inherited methods

Method Description Defined By
beginProfile() Marks the beginning of a code block for profiling. yii\mongodb\Command
endProfile() Marks the end of a code block for profiling. yii\mongodb\Command
log() Logs the command data if logging is enabled at $db. yii\mongodb\Command

Property Details

Hide inherited properties

$databaseName public property

Name of the database that this command is associated with.

public string $databaseName null
$db public property

The MongoDB connection that this command is associated with.

$document public property

Command document contents.

public array $document = []
$globalExecOptions public property

Default options for executeCommand method of MongoDB\Driver\Manager.

$readConcern public property

Read concern to be used in this command.

public \MongoDB\Driver\ReadConcern|string $readConcern null
$readPreference public property

Read preference. Note that the type of this property differs in getter and setter. See getReadPreference() and setReadPreference() for details.

public \MongoDB\Driver\ReadPreference $readPreference null
$writeConcern public property

Write concern to be used in this command. Note that the type of this property differs in getter and setter. See getWriteConcern() and setWriteConcern() for details.

public \MongoDB\Driver\WriteConcern|null $writeConcern 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);
    }
}

            
addDelete() public method

Adds the delete operation to the batch command.

See also executeBatch().

public $this addDelete ( $condition, $options = [] )
$condition array

Filter condition.

$options array

Delete options.

return $this

Self reference.

                public function addDelete($condition, $options = [])
{
    $this->document[] = [
        'type' => 'delete',
        'condition' => $this->db->getQueryBuilder()->buildCondition($condition),
        'options' => $options,
    ];
    return $this;
}

            
addInsert() public method

Adds the insert operation to the batch command.

See also executeBatch().

public $this addInsert ( $document )
$document array

Document to be inserted

return $this

Self reference.

                public function addInsert($document)
{
    $this->document[] = [
        'type' => 'insert',
        'document' => $document,
    ];
    return $this;
}

            
addUpdate() public method

Adds the update operation to the batch command.

See also executeBatch().

public $this addUpdate ( $condition, $document, $options = [] )
$condition array

Filter condition

$document array

Data to be updated

$options array

Update options.

return $this

Self reference.

                public function addUpdate($condition, $document, $options = [])
{
    $options = array_merge(
        [
            'multi' => true,
            'upsert' => false,
        ],
        $options
    );
    if ($options['multi']) {
        $keys = array_keys($document);
        if (!empty($keys) && strncmp('$', $keys[0], 1) !== 0) {
            $document = ['$set' => $document];
        }
    }
    $this->document[] = [
        'type' => 'update',
        'condition' => $this->db->getQueryBuilder()->buildCondition($condition),
        'document' => $document,
        'options' => $options,
    ];
    return $this;
}

            
aggregate() public method

Performs aggregation using MongoDB 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 ( $collectionName, $pipelines, $options = [], $execOptions = [] )
$collectionName string

Collection name

$pipelines array

List of pipeline operators.

$options array

Optional parameters.

$execOptions array

{@see \yii\mongodb\execute()}

return array|\MongoDB\Driver\Cursor

Aggregation result.

                public function aggregate($collectionName, $pipelines, $options = [], $execOptions = [])
{
    if (empty($options['cursor'])) {
        $returnCursor = false;
        $options['cursor'] = new \stdClass();
    } else {
        $returnCursor = true;
    }
    $this->document = $this->db->getQueryBuilder()->aggregate($collectionName, $pipelines, $options);
    $cursor = $this->execute($execOptions);
    if ($returnCursor) {
        return $cursor;
    }
    return $cursor->toArray();
}

            
batchInsert() public method

Inserts batch of new documents into collection.

public array|false batchInsert ( $collectionName, $documents, $options = [], $execOptions = [] )
$collectionName string

Collection name

$documents array[]

Documents list

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\executeBatch()}

return array|false

List of inserted IDs, false on failure.

                public function batchInsert($collectionName, $documents, $options = [], $execOptions = [])
{
    $this->document = [];
    foreach ($documents as $key => $document) {
        $this->document[$key] = [
            'type' => 'insert',
            'document' => $document
        ];
    }
    $result = $this->executeBatch($collectionName, $options, $execOptions);
    if ($result['result']->getInsertedCount() < 1) {
        return false;
    }
    return $result['insertedIds'];
}

            
beginProfile() protected method

Marks the beginning of a code block for profiling.

See also endProfile().

protected void beginProfile ( $token, $category )
$token string

Token for the code block

$category string

The category of this log message

                protected function beginProfile($token, $category)
{
    if ($token !== false && $this->db->enableProfiling) {
        Yii::beginProfile($token, $category);
    }
}

            
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

Counts records in specified collection.

public integer count ( $collectionName, $condition = [], $options = [], $execOptions = [] )
$collectionName string

Collection name

$condition array

Filter condition

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\execute()}

return integer

Records count

                public function count($collectionName, $condition = [], $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->count($collectionName, $condition, $options);
    $result = current($this->execute($execOptions)->toArray());
    return $result['n'];
}

            
createCollection() public method

Creates new collection in database associated with this command.s

public boolean createCollection ( $collectionName, array $options = [], $execOptions = [] )
$collectionName string

Collection name

$options array

Collection options in format: "name" => "value"

$execOptions array

{@see \yii\mongodb\execute()}

return boolean

Whether operation was successful.

                public function createCollection($collectionName, array $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->createCollection($collectionName, $options);
    $result = current($this->execute($execOptions)->toArray());
    return $result['ok'] > 0;
}

            
createIndexes() public method

Creates indexes in the collection.

public boolean createIndexes ( $collectionName, $indexes, $execOptions = [] )
$collectionName string

Collection name.

$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\execute()}

return boolean

Whether operation was successful.

                public function createIndexes($collectionName, $indexes, $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->createIndexes($this->databaseName, $collectionName, $indexes);
    $result = current($this->execute($execOptions)->toArray());
    return $result['ok'] > 0;
}

            
delete() public method

Removes documents from the collection.

public \MongoDB\Driver\WriteResult delete ( $collectionName, $condition, $options = [], $execOptions = [] )
$collectionName string

Collection name.

$condition array

Filter condition.

$options array

Delete options.

$execOptions array

{@see \yii\mongodb\executeBatch()}

return \MongoDB\Driver\WriteResult

Write result.

                public function delete($collectionName, $condition, $options = [], $execOptions = [])
{
    $batchOptions = [];
    foreach (['bypassDocumentValidation'] as $name) {
        if (isset($options[$name])) {
            $batchOptions[$name] = $options[$name];
            unset($options[$name]);
        }
    }
    $this->document = [];
    $this->addDelete($condition, $options);
    $result = $this->executeBatch($collectionName, $batchOptions, $execOptions);
    return $result['result'];
}

            
distinct() public method

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

public array distinct ( $collectionName, $fieldName, $condition = [], $options = [], $execOptions = [] )
$collectionName string

Collection name.

$fieldName string

Field name to use.

$condition array

Query parameters.

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\execute()}

return array

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

                public function distinct($collectionName, $fieldName, $condition = [], $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->distinct($collectionName, $fieldName, $condition, $options);
    $cursor = $this->execute($execOptions);
    $result = current($cursor->toArray());
    if (!isset($result['values']) || !is_array($result['values'])) {
        return false;
    }
    return $result['values'];
}

            
dropCollection() public method

Drops specified collection.

public boolean dropCollection ( $collectionName, $execOptions = [] )
$collectionName string

Name of the collection to be dropped.

$execOptions array

{@see \yii\mongodb\execute()}

return boolean

Whether operation was successful.

                public function dropCollection($collectionName, $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->dropCollection($collectionName);
    $result = current($this->execute($execOptions)->toArray());
    return $result['ok'] > 0;
}

            
dropDatabase() public method

Drops database associated with this command.

public boolean dropDatabase ( $execOptions = [] )
$execOptions array

{@see \yii\mongodb\execute()}

return boolean

Whether operation was successful.

                public function dropDatabase($execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->dropDatabase();
    $result = current($this->execute($execOptions)->toArray());
    return $result['ok'] > 0;
}

            
dropIndexes() public method

Drops collection indexes by name.

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

Collection name.

$indexes string

Wildcard for name of the indexes to be dropped.

$execOptions array

{@see \yii\mongodb\execute()}

return array

Result data.

                public function dropIndexes($collectionName, $indexes, $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->dropIndexes($collectionName, $indexes);
    return current($this->execute($execOptions)->toArray());
}

            
endProfile() protected method

Marks the end of a code block for profiling.

See also beginProfile().

protected void endProfile ( $token, $category )
$token string

Token for the code block

$category string

The category of this log message

                protected function endProfile($token, $category)
{
    if ($token !== false && $this->db->enableProfiling) {
        Yii::endProfile($token, $category);
    }
}

            
execute() public method
public \MongoDB\Driver\Cursor execute ( $execOptions = [] )
$execOptions array

(@see prepareExecCommandOptions()) Note: "readConcern" and "writeConcern" options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account

return \MongoDB\Driver\Cursor

Result cursor.

throws yii\mongodb\Exception

on failure.

                public function execute($execOptions = [])
{
    $this->prepareExecCommandOptions($execOptions);
    $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;
    $token = $this->log([$databaseName, 'command'], $this->document, __METHOD__);
    try {
        $this->beginProfile($token, __METHOD__);
        $this->db->open();
        $mongoCommand = new \MongoDB\Driver\Command($this->document);
        $cursor = $this->db->manager->executeCommand($databaseName, $mongoCommand, $execOptions);
        $cursor->setTypeMap($this->db->typeMap);
        $this->endProfile($token, __METHOD__);
    } catch (RuntimeException $e) {
        $this->endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), $e->getCode(), $e);
    }
    return $cursor;
}

            
executeBatch() public method
public array executeBatch ( $collectionName, $options = [], $execOptions = [] )
$collectionName string

Collection name.

$options array

Batch options.

$execOptions array

(@see prepareExecBulkWriteOptions())

return array

Array of 2 elements:

  • 'insertedIds' - contains inserted IDs.
  • 'result' - \MongoDB\Driver\WriteResult instance.
throws yii\mongodb\Exception

on failure.

throws yii\base\InvalidConfigException

on invalid $document format.

                public function executeBatch($collectionName, $options = [], $execOptions = [])
{
    $this->prepareExecBulkWriteOptions($execOptions);
    $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;
    $token = $this->log([$databaseName, $collectionName, 'bulkWrite'], $this->document, __METHOD__);
    try {
        $this->beginProfile($token, __METHOD__);
        $batch = new BulkWrite($options);
        $insertedIds = [];
        foreach ($this->document as $key => $operation) {
            switch ($operation['type']) {
                case 'insert':
                    $insertedIds[$key] = $batch->insert($operation['document']);
                    break;
                case 'update':
                    $batch->update($operation['condition'], $operation['document'], $operation['options']);
                    break;
                case 'delete':
                    $batch->delete($operation['condition'], isset($operation['options']) ? $operation['options'] : []);
                    break;
                default:
                    throw new InvalidConfigException("Unsupported batch operation type '{$operation['type']}'");
            }
        }
        $this->db->open();
        $writeResult = $this->db->manager->executeBulkWrite($databaseName . '.' . $collectionName, $batch, $execOptions);
        $this->endProfile($token, __METHOD__);
    } catch (RuntimeException $e) {
        $this->endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), $e->getCode(), $e);
    }
    return [
        'insertedIds' => $insertedIds,
        'result' => $writeResult,
    ];
}

            
explain() public method

Return an explanation of the query, often useful for optimization and debugging.

public array explain ( $collectionName, $query, $execOptions = [] )
$collectionName string

Collection name

$query array

Query document.

$execOptions array

{@see \yii\mongodb\execute()}

return array

Explanation of the query.

                public function explain($collectionName, $query, $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->explain($collectionName, $query);
    $cursor = $this->execute($execOptions);
    return current($cursor->toArray());
}

            
find() public method

Performs find query.

public \MongoDB\Driver\Cursor find ( $collectionName, $condition, $options = [], $execOptions = [] )
$collectionName string

Collection name

$condition array

Filter condition

$options array

Query options.

$execOptions array

{@see \yii\mongodb\query()}

return \MongoDB\Driver\Cursor

Result cursor.

                public function find($collectionName, $condition, $options = [], $execOptions = [])
{
    $queryBuilder = $this->db->getQueryBuilder();
    $this->document = $queryBuilder->buildCondition($condition);
    if (isset($options['projection'])) {
        $options['projection'] = $queryBuilder->buildSelectFields($options['projection']);
    }
    if (isset($options['sort'])) {
        $options['sort'] = $queryBuilder->buildSortFields($options['sort']);
    }
    if (array_key_exists('limit', $options)) {
        if ($options['limit'] === null || !ctype_digit((string) $options['limit'])) {
            unset($options['limit']);
        } else {
            $options['limit'] = (int)$options['limit'];
        }
    }
    if (array_key_exists('skip', $options)) {
        if ($options['skip'] === null || !ctype_digit((string) $options['skip'])) {
            unset($options['skip']);
        } else {
            $options['skip'] = (int)$options['skip'];
        }
    }
    return $this->query($collectionName, $options, $execOptions);
}

            
findAndModify() public method

Updates a document and returns it.

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

Query condition

$update array

Update criteria

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\execute()}

return array|null

The original document, or the modified document when $options['new'] is set.

                public function findAndModify($collectionName, $condition = [], $update = [], $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->findAndModify($collectionName, $condition, $update, $options);
    $cursor = $this->execute($execOptions);
    $result = current($cursor->toArray());
    if (!isset($result['value'])) {
        return null;
    }
    return $result['value'];
}

            
group() public method

Performs aggregation using MongoDB "group" command.

public array group ( $collectionName, $keys, $initial, $reduce, $options = [], $execOptions = [] )
$collectionName string

Collection name.

$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\execute()}

return array

The result of the aggregation.

                public function group($collectionName, $keys, $initial, $reduce, $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->group($collectionName, $keys, $initial, $reduce, $options);
    $cursor = $this->execute($execOptions);
    $result = current($cursor->toArray());
    return $result['retval'];
}

            
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

Inserts new document into collection.

public \MongoDB\BSON\ObjectID|boolean insert ( $collectionName, $document, $options = [], $execOptions = [] )
$collectionName string

Collection name

$document array

Document content

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\executeBatch()}

return \MongoDB\BSON\ObjectID|boolean

Inserted record ID, false - on failure.

                public function insert($collectionName, $document, $options = [], $execOptions = [])
{
    $this->document = [];
    $this->addInsert($document);
    $result = $this->executeBatch($collectionName, $options, $execOptions);
    if ($result['result']->getInsertedCount() < 1) {
        return false;
    }
    return reset($result['insertedIds']);
}

            
listCollections() public method

Returns the list of available collections.

public array listCollections ( $condition = [], $options = [], $execOptions = [] )
$condition array

Filter condition.

$options array

Options list.

$execOptions array

{@see \yii\mongodb\execute()}

return array

Collections information.

                public function listCollections($condition = [], $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->listCollections($condition, $options);
    $cursor = $this->execute($execOptions);
    return $cursor->toArray();
}

            
listDatabases() public method

Returns the list of available databases.

public array listDatabases ( $condition = [], $options = [], $execOptions = [] )
$condition array

Filter condition.

$options array

Options list.

$execOptions array

{@see \yii\mongodb\execute()}

return array

Database information

                public function listDatabases($condition = [], $options = [], $execOptions = [])
{
    if ($this->databaseName === null) {
        $this->databaseName = 'admin';
    }
    $this->document = $this->db->getQueryBuilder()->listDatabases($condition, $options);
    $cursor = $this->execute($execOptions);
    $result = current($cursor->toArray());
    if (empty($result['databases'])) {
        return [];
    }
    return $result['databases'];
}

            
listIndexes() public method

Returns information about current collection indexes.

public array listIndexes ( $collectionName, $options = [], $execOptions = [] )
$collectionName string

Collection name

$options array

List of options in format: optionName => optionValue.

$execOptions array

{@see \yii\mongodb\execute()}

return array

List of indexes info.

throws yii\mongodb\Exception

on failure.

                public function listIndexes($collectionName, $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->listIndexes($collectionName, $options);
    try {
        $cursor = $this->execute($execOptions);
    } catch (Exception $e) {
        // The server may return an error if the collection does not exist.
        $notFoundCodes = [
            26, // namespace not found
            60 // database not found
        ];
        if (in_array($e->getCode(), $notFoundCodes, true)) {
            return [];
        }
        throw $e;
    }
    return $cursor->toArray();
}

            
log() protected method

Logs the command data if logging is enabled at $db.

protected string|false log ( $namespace, $data, $category )
$namespace array|string

Command namespace.

$data array

Command data.

$category string

Log category

return string|false

Log token, false if log is not enabled.

                protected function log($namespace, $data, $category)
{
    if ($this->db->enableLogging) {
        $token = $this->db->getLogBuilder()->generateToken($namespace, $data);
        Yii::info($token, $category);
        return $token;
    }
    return false;
}

            
mapReduce() public method

Performs MongoDB "map-reduce" command.

public string|array mapReduce ( $collectionName, $map, $reduce, $out, $condition = [], $options = [], $execOptions = [] )
$collectionName string

Collection name.

$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

Filter condition 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\execute()}

return string|array

The map reduce output collection name or output results.

                public function mapReduce($collectionName, $map, $reduce, $out, $condition = [], $options = [], $execOptions = [])
{
    $this->document = $this->db->getQueryBuilder()->mapReduce($collectionName, $map, $reduce, $out, $condition, $options);
    $cursor = $this->execute($execOptions);
    $result = current($cursor->toArray());
    return array_key_exists('results', $result) ? $result['results'] : $result['result'];
}

            
prepareManagerOptions() public static method

Preapare Concern and Preference options for easy use

public static void prepareManagerOptions ( &$options )
$options array|object

By reference convert string option to object ['readConcern' => 'snapshot'] > ['readConcern' => new \MongoDB\Driver\ReadConcern('snapshot')] ['writeConcern' => 'majority'] > ['writeConcern' => new \MongoDB\Driver\WriteConcern('majority')] ['writeConcern' => ['majority',true]] > ['writeConcern' => new \MongoDB\Driver\WriteConcern('majority',true)] ['readPreference' => 'snapshot'] > ['readPreference' => new \MongoDB\Driver\ReadPreference('primary')] {@see https://www.php.net/manual/en/mongodb-driver-manager.executecommand.php#refsect1-mongodb-driver-manager.executecommand-parameters} {@see https://www.php.net/manual/en/mongodb-driver-manager.executebulkwrite.php#refsect1-mongodb-driver-manager.executebulkwrite-parameters} {@see https://www.php.net/manual/en/mongodb-driver-server.executequery.php#refsect1-mongodb-driver-server.executequery-parameters}

                public static function prepareManagerOptions(&$options)
{
    //Convert readConcern option
    if (array_key_exists('readConcern', $options) && is_string($options['readConcern'])) {
        $options['readConcern'] = new ReadConcern($options['readConcern']);
    }
    //Convert writeConcern option
    if (array_key_exists('writeConcern', $options)) {
        if (is_string($options['writeConcern']) || is_int($options['writeConcern'])) {
            $options['writeConcern'] = new WriteConcern($options['writeConcern']);
        } elseif (is_array($options['writeConcern'])) {
            $options['writeConcern'] = (new \ReflectionClass('\MongoDB\Driver\WriteConcern'))->newInstanceArgs($options['writeConcern']);   
        }
    }
    //Convert readPreference option
    if (array_key_exists('readPreference', $options)) {
        if (is_string($options['readPreference'])) {
            $options['readPreference'] = new ReadPreference($options['readPreference']);
        } elseif (is_array($options['readPreference'])) {
            $options['readPreference'] = (new \ReflectionClass('\MongoDB\Driver\ReadPreference'))->newInstanceArgs($options['readPreference']);
        }
    }
    //Convert session option
    if (array_key_exists('session', $options) && $options['session'] instanceof ClientSession) {
        $options['session'] = $options['session']->mongoSession;
    }


            
query() public method

Executes this command as a mongo query

public \MongoDB\Driver\Cursor query ( $collectionName, $options = [], $execOptions = [] )
$collectionName string

Collection name

$options array

Query options.

$execOptions array

(@see prepareExecQueryOptions())

return \MongoDB\Driver\Cursor

Result cursor.

throws yii\mongodb\Exception

on failure

                public function query($collectionName, $options = [], $execOptions = [])
{
    $this->prepareExecQueryOptions($execOptions);
    $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;
    $token = $this->log(
        'find',
        array_merge(
            [
                'ns' => $databaseName . '.' . $collectionName,
                'filter' => $this->document,
            ],
            $options
        ),
        __METHOD__
    );
    try {
        $this->beginProfile($token, __METHOD__);
        $query = new \MongoDB\Driver\Query($this->document, $options);
        $this->db->open();
        $cursor = $this->db->manager->executeQuery($databaseName . '.' . $collectionName, $query, $execOptions);
        $cursor->setTypeMap($this->db->typeMap);
        $this->endProfile($token, __METHOD__);
    } catch (RuntimeException $e) {
        $this->endProfile($token, __METHOD__);
        throw new Exception($e->getMessage(), $e->getCode(), $e);
    }
    return $cursor;
}

            
update() public method

Update existing documents in the collection.

public \MongoDB\Driver\WriteResult update ( $collectionName, $condition, $document, $options = [], $execOptions = [] )
$collectionName string

Collection name

$condition array

Filter condition

$document array

Data to be updated.

$options array

Update options.

$execOptions array

{@see \yii\mongodb\executeBatch()}

return \MongoDB\Driver\WriteResult

Write result.

                public function update($collectionName, $condition, $document, $options = [], $execOptions = [])
{
    $batchOptions = [];
    foreach (['bypassDocumentValidation'] as $name) {
        if (isset($options[$name])) {
            $batchOptions[$name] = $options[$name];
            unset($options[$name]);
        }
    }
    $this->document = [];
    $this->addUpdate($condition, $document, $options);
    $result = $this->executeBatch($collectionName, $batchOptions, $execOptions);
    return $result['result'];
}