Docs Menu

Docs HomePHP Library Manual

Execute Database Commands

On this page

  • Overview
  • Commands That Return a Single Result Document
  • Commands That Yield Multiple Results
  • Specifying a Custom Read Preference

The MongoDB PHP Library provides helper methods across the Client, Database, and Collection classes for common database commands. In addition, the MongoDB\Database::command() method may be used to run database commands that do not have a helper method.

The MongoDB\Database::command() method always returns a MongoDB\Driver\Cursor object, since it must support execution of commands that return single result documents and multiple results via a command cursor.

Most database commands return a single result document, which can be obtained by converting the returned cursor to an array and accessing its first element. The following example executes a ping command and prints its result document:

<?php
$database = (new MongoDB\Client)->test;
$cursor = $database->command(['ping' => 1]);
var_dump($cursor->toArray()[0]);

The output would resemble:

object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}

Some database commands return a cursor with multiple results. The following example executes listCollections, which returns a cursor containing a result document for each collection in the test database, and iterates through the results using a foreach loop. Note that this example is illustrative; applications would generally use MongoDB\Database::listCollections() in practice.

<?php
$database = (new MongoDB\Client)->test;
$cursor = $database->command(['listCollections' => 1]);
foreach ($cursor as $collection) {
echo $collection['name'], "\n";
}

The output might resemble the following:

persons
posts
zips

Note

At the protocol level, commands that yield multiple results via a cursor will return a single result document with the essential ingredients for constructing the cursor (i.e. the cursor's ID, namespace, and an optional first batch of results). If the MongoDB\Driver\Manager::executeCommand() method in the PHP driver detects such a response, it will construct an iterable command cursor and return it instead of the raw result document. If necessary, raw result documents can still be observed using command monitoring.

Write commands, such as createUser, can only be executed on a writable server (e.g. primary replica set member). Command helper methods in the MongoDB PHP Library, such as MongoDB\Database::drop(), know to apply their own read preference if necessary. However, the MongoDB\Database::command() method is a generic method and defaults to the read preference of the Database object on which it is invoked. When necessary, the readPreference option may be used to override the default read preference.

The following example connects to a cluster and specifies secondaryPreferred as the Client's default read preference. It then specifies a primary read preference when executing the createUser command on the test database:

<?php
$client = new MongoDB\Client(
'mongodb+srv://cluster0.example.com',
['readPreference' => 'secondaryPreferred']
);
$client->test;
$cursor = $db->command(
[
'createUser' => 'username',
'pwd' => 'password',
'roles' => ['readWrite'],
],
[
'readPreference' => new MongoDB\Driver\ReadPreference('primary'),
]
);
var_dump($cursor->toArray()[0]);

The output would then resemble:

object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
←  CollationCustom Data-Types →