# Class yii\mongodb\Command

Inheritance | yii\mongodb\Command » yii\base\BaseObject
Implements | yii\base\Configurable
Available since version | 2.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
$readConcern | \MongoDB\Driver\ReadConcern|string | Read concern to be used in this command. | yii\mongodb\Command
$readPreference | \MongoDB\Driver\ReadPreference | Read preference. Note that the type of this property differs in getter and setter. See getReadPreference() and setReadPreference() for details. | yii\mongodb\Command
$writeConcern | \MongoDB\Driver\WriteConcern|null | 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. | 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
getReadConcern() | Retuns read concern for this command. | yii\mongodb\Command
getReadPreference() | Returns read preference for this command. | yii\mongodb\Command
getWriteConcern() | Returns write concern for this command. | 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
query() | Executes this command as a mongo query | yii\mongodb\Command
setReadConcern() | Sets read concern for this command. | yii\mongodb\Command
setReadPreference() | Sets read preference for this command. | yii\mongodb\Command
setWriteConcern() | Sets write concern for this command. | 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

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

public yii\mongodb\Connection $db = null
$document public property

Command document contents.

public array $document = []
$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

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.

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.

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.

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 = [] )
$collectionName | string | Collection name
$pipelines | array | List of pipeline operators.
$options | array | Optional parameters.
return | array|\MongoDB\Driver\Cursor | Aggregation result.

batchInsert() public method

Inserts batch of new documents into collection.

public array|false batchInsert ( $collectionName, $documents, $options = [] )
$collectionName | string | Collection name
$documents | array[] | Documents list
$options | array | List of options in format: optionName => optionValue.
return | array|false | List of inserted IDs, `false` on failure.

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

count() public method

Counts records in specified collection.

public integer count ( $collectionName, $condition = [], $options = [] )
$collectionName | string | Collection name
$condition | array | Filter condition
$options | array | List of options in format: optionName => optionValue.
return | integer | Records count

createCollection() public method

Creates new collection in database associated with this command.s

public boolean createCollection ( $collectionName, array $options = [] )
$collectionName | string | Collection name
$options | array | Collection options in format: "name" => "value"
return | boolean | Whether operation was successful.

createIndexes() public method

Creates indexes in the collection.

public boolean createIndexes ( $collectionName, $indexes )
$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.

return | boolean | Whether operation was successful.

delete() public method

Removes documents from the collection.

public \MongoDB\Driver\WriteResult delete ( $collectionName, $condition, $options = [] )
$collectionName | string | Collection name.
$condition | array | Filter condition.
$options | array | Delete options.
return | \MongoDB\Driver\WriteResult | Write result.

distinct() public method

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

public array distinct ( $collectionName, $fieldName, $condition = [], $options = [] )
$collectionName | string | Collection name.
$fieldName | string | Field name to use.
$condition | array | Query parameters.
$options | array | List of options in format: optionName => optionValue.
return | array | Array of distinct values, or "false" on failure.

dropCollection() public method

Drops specified collection.

public boolean dropCollection ( $collectionName )
$collectionName | string | Name of the collection to be dropped.
return | boolean | Whether operation was successful.

dropDatabase() public method

Drops database associated with this command.

public boolean dropDatabase ( )
return | boolean | Whether operation was successful.

dropIndexes() public method

Drops collection indexes by name.

public array dropIndexes ( $collectionName, $indexes )
$collectionName | string | Collection name.
$indexes | string | Wildcard for name of the indexes to be dropped.
return | array | Result data.

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

execute() public method

Executes this command.

public \MongoDB\Driver\Cursor execute ( )
return | \MongoDB\Driver\Cursor | Result cursor.
throws | yii\mongodb\Exception | on failure.

executeBatch() public method

Execute commands batch (bulk).

public array executeBatch ( $collectionName, $options = [] )
$collectionName | string | Collection name.
$options | array | Batch options.

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.

explain() public method

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

public array explain ( $collectionName, $query )
$collectionName | string | Collection name
$query | array | Query document.
return | array | Explanation of the query.

find() public method

Performs find query.

public \MongoDB\Driver\Cursor find ( $collectionName, $condition, $options = [] )
$collectionName | string | Collection name
$condition | array | Filter condition
$options | array | Query options.
return | \MongoDB\Driver\Cursor | Result cursor.

findAndModify() public method

Updates a document and returns it.

public array|null findAndModify ( $collectionName, $condition = [], $update = [], $options = [] )
$collectionName |  |
$condition | array | Query condition
$update | array | Update criteria
$options | array | List of options in format: optionName => optionValue.
return | array|null | The original document, or the modified document when $options['new'] is set.

getReadConcern() public method

Retuns read concern for this command.

public \MongoDB\Driver\ReadConcern|string getReadConcern ( )
return | \MongoDB\Driver\ReadConcern|string | Read concern to be used in this command.

getReadPreference() public method

Returns read preference for this command.

public \MongoDB\Driver\ReadPreference getReadPreference ( )
return | \MongoDB\Driver\ReadPreference | Read preference.

getWriteConcern() public method

Returns write concern for this command.

public \MongoDB\Driver\WriteConcern|null getWriteConcern ( )
return | \MongoDB\Driver\WriteConcern|null | Write concern to be used in this command.

group() public method

Performs aggregation using MongoDB "group" command.

public array group ( $collectionName, $keys, $initial, $reduce, $options = [] )
$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.

return | array | The result of the aggregation.

insert() public method

Inserts new document into collection.

public \MongoDB\BSON\ObjectID|boolean insert ( $collectionName, $document, $options = [] )
$collectionName | string | Collection name
$document | array | Document content
$options | array | List of options in format: optionName => optionValue.
return | \MongoDB\BSON\ObjectID|boolean | Inserted record ID, `false` - on failure.

listCollections() public method

Returns the list of available collections.

public array listCollections ( $condition = [], $options = [] )
$condition | array | Filter condition.
$options | array | Options list.
return | array | Collections information.

listDatabases() public method

Returns the list of available databases.

public array listDatabases ( $condition = [], $options = [] )
$condition | array | Filter condition.
$options | array | Options list.
return | array | Database information

listIndexes() public method

Returns information about current collection indexes.

public array listIndexes ( $collectionName, $options = [] )
$collectionName | string | Collection name
$options | array | List of options in format: optionName => optionValue.
return | array | List of indexes info.
throws | yii\mongodb\Exception | on failure.

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.

mapReduce() public method

Performs MongoDB "map-reduce" command.

public string|array mapReduce ( $collectionName, $map, $reduce, $out, $condition = [], $options = [] )
$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.

return | string|array | The map reduce output collection name or output results.

query() public method

Executes this command as a mongo query

public \MongoDB\Driver\Cursor query ( $collectionName, $options = [] )
$collectionName | string | Collection name
$options | array | Query options.
return | \MongoDB\Driver\Cursor | Result cursor.
throws | yii\mongodb\Exception | on failure

setReadConcern() public method

Sets read concern for this command.

public $this setReadConcern ( $readConcern )
$readConcern | \MongoDB\Driver\ReadConcern|string | Read concern, it can be an instance of ReadConcern or scalar level value, for example: 'local'.
return | $this | Self reference

setReadPreference() public method

Sets read preference for this command.

public $this setReadPreference ( $readPreference )
$readPreference | \MongoDB\Driver\ReadPreference|integer|string|null | Read reference, it can be specified as instance of ReadPreference or scalar mode value, for example: `ReadPreference::RP_PRIMARY`.
return | $this | Self reference.

setWriteConcern() public method

Sets write concern for this command.

public $this setWriteConcern ( $writeConcern )
$writeConcern | \MongoDB\Driver\WriteConcern|integer|string|null | Write concern, it can be an instance of WriteConcern or its scalar mode value, for example: `majority`.
return | $this | Self reference

update() public method

Update existing documents in the collection.

public \MongoDB\Driver\WriteResult update ( $collectionName, $condition, $document, $options = [] )
$collectionName | string | Collection name
$condition | array | Filter condition
$document | array | Data to be updated.
$options | array | Update options.
return | \MongoDB\Driver\WriteResult | Write result.