(mongodb >=1.0.0)
MongoDB\Driver\Manager::executeCommand — Execute a database command
$db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
Selects a server according to the "readPreference" option
and executes the command on that server.
This method applies no special logic to the command. The
Default values for the "readPreference",
"readConcern", and "writeConcern"
options will be inferred from an active transaction (indicated by the
"session" option). If there is no active transaction, a
primary read preference will be used for server selection.
Default values will not be inferred from the connection URI. Users are therefore encouraged to use specific read and/or write command methods if possible.
db (string)Назва бази даних, в якій буде виконано команду.
command (MongoDB\Driver\Command)Команда, яку потрібно виконати.
options
| Option | Type | Description |
|---|---|---|
| readConcern | MongoDB\Driver\ReadConcern |
Вимога щодо зчитування. Цей параметр доступний в MongoDB 3.2+, тож його застосування у старіших версіях викине виключення під час виконання. |
| readPreference | MongoDB\Driver\ReadPreference |
Параметр читання для вибору сервера для операції. |
| session | MongoDB\Driver\Session |
Сеанс, по'язаний з операцією. |
| writeConcern | MongoDB\Driver\WriteConcern |
Вимога щодо запису. |
Для сеансу ("session") транзакції, яка триває, не
можна задати параметр "readConcern" або
"writeConcern". Це призведе до викидання виключення
MongoDB\Driver\Exception\InvalidArgumentException.
Ці два параметри потрібно задавати під час створення транзакції методом
MongoDB\Driver\Session::startTransaction().
У разі успіху повертає примірника MongoDB\Driver\Cursor.
"session" використано разом з параметром
"readConcern" або "writeConcern",
викидається
MongoDB\Driver\Exception\InvalidArgumentException."session", а вимога щодо запису не задоволена, викидається
MongoDB\Driver\Exception\InvalidArgumentException.
| Версія | Опис |
|---|---|
| PECL mongodb 2.0.0 |
The options parameter no longer accepts a
MongoDB\Driver\ReadPreference instance.
|
| PECL mongodb 1.21.0 |
Passing a MongoDB\Driver\ReadPreference object as
options is deprecated and will be removed in 2.0.
|
| PECL mongodb 1.4.4 |
MongoDB\Driver\Exception\InvalidArgumentException
will be thrown if the "session" option is used in
combination with an unacknowledged write concern.
|
| PECL mongodb 1.4.0 |
The third parameter is now an options array.
For backwards compatibility, this paramater will still accept a
MongoDB\Driver\ReadPreference object.
|
Приклад #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)
}
Приклад #3 Limiting execution time for a command
The execution time of a command may be limited by specifying a value for
"maxTimeMS" in the
MongoDB\Driver\Command document. Note that this time
limit is enforced on the server side and does not take network latency into
account. See
» Terminate Running Operations
in the MongoDB manual for more information.
<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command([
'count' => 'collection',
'query' => ['x' => ['$gt' => 1]],
'maxTimeMS' => 1000,
]);
$cursor = $manager->executeCommand('db', $command);
var_dump($cursor->toArray()[0]);
?>If the command fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.
Зауваження: If a secondary
readPreferenceis used, it is the caller's responsibility to ensure that thecommandcan be executed on a secondary. No validation is done by the driver.
Зауваження: This method does not default to using the read preference from the MongoDB Connection URI. Applications in need of that behavior should consider using MongoDB\Driver\Manager::executeReadCommand().