- Reference >
- MongoDB\Database Class >
- MongoDB\Database::command()
MongoDB\Database::command()
On this page
Definition
-
MongoDB\Database::command
Execute a command on the database. This is generally used to execute commands that do not have a corresponding helper method within the library.
This method has the following parameters:
Parameter Type Description $command
array|object The database command document. $options
array Optional. An array specifying the desired options. The
$options
parameter supports the following options:Option Type Description readPreference
MongoDB\Driver\ReadPreference Optional. Read preference to use for the operation. Defaults to the database’s read preference. session
MongoDB\Driver\Session Optional. Client session to associate with the operation.
New in version 1.3.
typeMap
array Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the database’s type map.
Return Values
A MongoDB\Driver\Cursor object.
Errors/Exceptions
MongoDB\Exception\InvalidArgumentException
for errors related to
the parsing of parameters or options.
MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).
Example
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:
The output would resemble:
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. Note that this example is illustrative; applications would
generally use MongoDB\Database::listCollections()
in practice.
The output would resemble: