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

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.

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 __call( string $name, array $params ): mixed
$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 __construct( array<string, mixed> $config = [] ): mixed
$config array<string, mixed>

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 __get( string $name ): mixed
$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 __isset( string $name ): boolean
$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 __set( string $name, mixed $value ): mixed
$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 __unset( string $name ): mixed
$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 addDelete( array $condition, array $options = [] ): $this
$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 addInsert( array $document ): $this
$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 addUpdate( array $condition, array $document, array $options = [] ): $this
$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 aggregate( string $collectionName, array $pipelines, array $options = [], array $execOptions = [] ): array|\MongoDB\Driver\Cursor
$collectionName string

Collection name

$pipelines array

List of pipeline operators.

$options array

Optional parameters.

$execOptions array

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 batchInsert( string $collectionName, array[] $documents, array $options = [], array $execOptions = [] ): array|false
$collectionName string

Collection name

$documents array[]

Documents list

$options array

List of options in format: optionName => optionValue.

$execOptions array

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 beginProfile( string $token, string $category ): mixed
$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 canGetProperty( string $name, boolean $checkVars = true ): boolean
$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 canSetProperty( string $name, boolean $checkVars = true ): boolean
$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 className( ): string
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 count( string $collectionName, array $condition = [], array $options = [], array $execOptions = [] ): integer
$collectionName string

Collection name

$condition array

Filter condition

$options array

List of options in format: optionName => optionValue.

$execOptions array

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 createCollection( string $collectionName, array $options = [], array $execOptions = [] ): boolean
$collectionName string

Collection name

$options array

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

$execOptions array

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 createIndexes( string $collectionName, array[] $indexes, array $execOptions = [] ): boolean
$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

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 delete( string $collectionName, array $condition, array $options = [], array $execOptions = [] ): \MongoDB\Driver\WriteResult
$collectionName string

Collection name.

$condition array

Filter condition.

$options array

Delete options.

$execOptions array

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 distinct( string $collectionName, string $fieldName, array $condition = [], array $options = [], array $execOptions = [] ): array
$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

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 dropCollection( string $collectionName, array $execOptions = [] ): boolean
$collectionName string

Name of the collection to be dropped.

$execOptions array

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 dropDatabase( array $execOptions = [] ): boolean
$execOptions array

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 dropIndexes( string $collectionName, string $indexes, array $execOptions = [] ): array
$collectionName string

Collection name.

$indexes string

Wildcard for name of the indexes to be dropped.

$execOptions array

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 endProfile( string $token, string $category ): mixed
$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 execute( array $execOptions = [] ): \MongoDB\Driver\Cursor
$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 executeBatch( string $collectionName, array $options = [], array $execOptions = [] ): array
$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 explain( string $collectionName, array $query, array $execOptions = [] ): array
$collectionName string

Collection name

$query array

Query document.

$execOptions array

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

Collection name

$condition array

Filter condition

$options array

Query options.

$execOptions array

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 findAndModify( mixed $collectionName, array $condition = [], array $update = [], array $options = [], array $execOptions = [] ): array|null
$collectionName mixed
$condition array

Query condition

$update array

Update criteria

$options array

List of options in format: optionName => optionValue.

$execOptions array

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 group( string $collectionName, mixed $keys, array $initial, \MongoDB\BSON\Javascript|string $reduce, array $options = [], array $execOptions = [] ): array
$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

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 hasMethod( string $name ): boolean
$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 hasProperty( string $name, boolean $checkVars = true ): boolean
$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 init( ): mixed

                public function init()
{
}

            
insert() public method

Inserts new document into collection.

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

Collection name

$document array

Document content

$options array

List of options in format: optionName => optionValue.

$execOptions array

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 listCollections( array $condition = [], array $options = [], array $execOptions = [] ): array
$condition array

Filter condition.

$options array

Options list.

$execOptions array

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 listDatabases( array $condition = [], array $options = [], array $execOptions = [] ): array
$condition array

Filter condition.

$options array

Options list.

$execOptions array

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 listIndexes( string $collectionName, array $options = [], array $execOptions = [] ): array
$collectionName string

Collection name

$options array

List of options in format: optionName => optionValue.

$execOptions array

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 log( array|string $namespace, array $data, string $category ): string|false
$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 mapReduce( string $collectionName, \MongoDB\BSON\Javascript|string $map, \MongoDB\BSON\Javascript|string $reduce, string|array $out, array $condition = [], array $options = [], array $execOptions = [] ): string|array
$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

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 prepareManagerOptions( array|object & $options ): mixed
$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')] https://www.php.net/manual/en/mongodb-driver-manager.executecommand.php#refsect1-mongodb-driver-manager.executecommand-parameters https://www.php.net/manual/en/mongodb-driver-manager.executebulkwrite.php#refsect1-mongodb-driver-manager.executebulkwrite-parameters 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 query( string $collectionName, array $options = [], array $execOptions = [] ): \MongoDB\Driver\Cursor
$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 update( string $collectionName, array $condition, array $document, array $options = [], array $execOptions = [] ): \MongoDB\Driver\WriteResult
$collectionName string

Collection name

$condition array

Filter condition

$document array

Data to be updated.

$options array

Update options.

$execOptions array

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