(mongodb >=1.0.0)
MongoDB\Driver\Manager::executeCommand — Execute a database command
$db
, MongoDB\Driver\Command $command
[, MongoDB\Driver\ReadPreference $readPreference
] )
Executes command
on a server If
readPreference
is provided, it will be used for server
selection; otherwise, the default read preference will be used.
db
(string)Имя базы данных, в которой запускается комманда.
command
(MongoDB\Driver\Command)MongoDB\Driver\Command для выполнения.
readPreference
(MongoDB\Driver\ReadPreference)Опционально MongoDB\Driver\ReadPreference для выбора сервера для этой операции. Если не задано, то он будет выбран из URI соединения MongoDB.
В случае успеха возвращает MongoDB\Driver\Cursor.
Пример #1 MongoDB\Driver\Manager::executeCommand() with a command returning a single result document
<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);
try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
/* The ping command returns a single result document, so we need to access the
* first result in the cursor. */
$response = $cursor->toArray()[0];
var_dump($response);
?>
Результат выполнения данного примера:
array(1) { ["ok"]=> float(1) }
Пример #2 MongoDB\Driver\Manager::executeCommand() with a command returning a cursor
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);
$command = new MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => [
['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
],
'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);
/* The aggregate command can optionally return its results in a cursor instead
* of a single result document. In this case, we can iterate on the cursor
* directly to access those results. */
foreach ($cursor as $document) {
var_dump($document);
}
?>
Результат выполнения данного примера:
object(stdClass)#6 (2) { ["_id"]=> string(3) "bar" ["sum"]=> int(10) } object(stdClass)#7 (2) { ["_id"]=> string(3) "foo" ["sum"]=> int(2) }
Замечание:
This method does not take a MongoDB\Driver\WriteConcern parameter. For write commands (e.g. » findAndModify in MongoDB 3.2+), the write concern should be included in the
command
document itself.If a secondary
readPreference
is used, it is the caller's responsibility to ensure that thecommand
can be executed on a secondary. No validation is done by the driver.