Class yii\mongodb\Command
Inheritance | yii\mongodb\Command » yii\base\BaseObject |
---|---|
Available since extension's version | 2.1 |
Source Code | https://github.com/yiisoft/yii2-mongodb/blob/master/src/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
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
Method | Description | Defined By |
---|---|---|
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 |
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 |
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
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
Name of the database that this command is associated with.
The MongoDB connection that this command is associated with.
Default options for executeCommand
method of MongoDB\Driver\Manager.
Read concern to be used in this command.
Read preference. Note that the type of this property differs in getter and setter. See getReadPreference() and setReadPreference() for details.
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.
Method Details
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;
}
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;
}
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;
}
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();
}
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, |
---|
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'];
}
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);
}
}
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'];
}
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;
}
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:
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;
}
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'];
}
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'];
}
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;
}
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;
}
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());
}
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);
}
}
Executes this command.
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;
}
Execute commands batch (bulk).
public array executeBatch ( $collectionName, $options = [], $execOptions = [] ) | ||
$collectionName | string |
Collection name. |
$options | array |
Batch options. |
$execOptions | array |
(@see prepareExecBulkWriteOptions()) |
return | array |
Array of 2 elements:
|
---|---|---|
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,
];
}
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());
}
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);
}
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'];
}
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:
|
$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'];
}
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, |
---|
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']);
}
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();
}
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'];
}
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();
}
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, |
---|
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;
}
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:
|
$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'];
}
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;
}
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 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'];
}