=========================
Execute Database Commands
=========================

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 2
   :class: singlecol

Overview
--------

The |php-library| provides helper methods across the :phpclass:`Client
<MongoDB\\Client>`, :phpclass:`Database <MongoDB\\Database>`, and
:phpclass:`Collection <MongoDB\\Collection>` classes for common
:manual:`database commands </reference/command>`. In addition, the
:phpmethod:`MongoDB\\Database::command()` method may be used to run database
commands that do not have a helper method.

Execute Database Commands
-------------------------

Basic Command
~~~~~~~~~~~~~

To execute a command on a :program:`mongod` instance, use the
:phpmethod:`MongoDB\\Database::command()` method. For instance, the following
operation uses the :manual:`geoNear </reference/command/geoNear>` command to
search for the three closest documents to longitude ``-74`` and latitude ``40``
in the ``restos`` collection in the ``test`` database:

.. code-block:: php

   <?php

   $database = (new MongoDB\Client)->test;

   $cursor = $database->command([
       'geoNear' => 'restos',
       'near' => [
           'type' => 'Point',
           'coordinates' => [-74.0, 40.0],
       ],
       'spherical' => 'true',
       'num' => 3,
   ]);

   $results = $cursor->toArray()[0];

   var_dump($results);

The output would then resemble::

   object(MongoDB\Model\BSONDocument)#27 (1) {
     ["storage":"ArrayObject":private]=>
     array(4) {
       ["waitedMS"]=>
       int(0)
       ["results"]=>
       object(MongoDB\Model\BSONArray)#25 (1) {
         ["storage":"ArrayObject":private]=>
         array(3) {
           [0]=>
           object(MongoDB\Model\BSONDocument)#14 (1) {
             ["storage":"ArrayObject":private]=>
             array(2) {
               ["dis"]=>
               float(39463.618389163)
               ["obj"]=>
               object(MongoDB\Model\BSONDocument)#13 (1) {
                 ["storage":"ArrayObject":private]=>
                 array(3) {
                   ["_id"]=>
                   object(MongoDB\BSON\ObjectId)#3 (1) {
                     ["oid"]=>
                     string(24) "55cba2486c522cafdb059bed"
                   }
                   ["location"]=>
                   object(MongoDB\Model\BSONDocument)#12 (1) {
                     ["storage":"ArrayObject":private]=>
                     array(2) {
                       ["coordinates"]=>
                       object(MongoDB\Model\BSONArray)#11 (1) {
                         ["storage":"ArrayObject":private]=>
                         array(2) {
                           [0]=>
                           float(-74.1641319)
                           [1]=>
                           float(39.6686512)
                         }
                       }
                       ["type"]=>
                       string(5) "Point"
                     }
                   }
                   ["name"]=>
                   string(32) "Soul Food Kitchen Seafood Heaven"
                 }
               }
             }
           }
           [1]=>
           object(MongoDB\Model\BSONDocument)#19 (1) {
             ["storage":"ArrayObject":private]=>
             array(2) {
               ["dis"]=>
               float(50686.851650416)
               ["obj"]=>
               object(MongoDB\Model\BSONDocument)#18 (1) {
                 ["storage":"ArrayObject":private]=>
                 array(3) {
                   ["_id"]=>
                   object(MongoDB\BSON\ObjectId)#15 (1) {
                     ["oid"]=>
                     string(24) "55cba2476c522cafdb0544df"
                   }
                   ["location"]=>
                   object(MongoDB\Model\BSONDocument)#17 (1) {
                     ["storage":"ArrayObject":private]=>
                     array(2) {
                       ["coordinates"]=>
                       object(MongoDB\Model\BSONArray)#16 (1) {
                         ["storage":"ArrayObject":private]=>
                         array(2) {
                           [0]=>
                           float(-74.2566332)
                           [1]=>
                           float(40.4109872)
                         }
                       }
                       ["type"]=>
                       string(5) "Point"
                     }
                   }
                   ["name"]=>
                   string(20) "Seguine Bagel Bakery"
                 }
               }
             }
           }
           [2]=>
           object(MongoDB\Model\BSONDocument)#24 (1) {
             ["storage":"ArrayObject":private]=>
             array(2) {
               ["dis"]=>
               float(58398.379630263)
               ["obj"]=>
               object(MongoDB\Model\BSONDocument)#23 (1) {
                 ["storage":"ArrayObject":private]=>
                 array(3) {
                   ["_id"]=>
                   object(MongoDB\BSON\ObjectId)#20 (1) {
                     ["oid"]=>
                     string(24) "55cba2476c522cafdb053c92"
                   }
                   ["location"]=>
                   object(MongoDB\Model\BSONDocument)#22 (1) {
                     ["storage":"ArrayObject":private]=>
                     array(2) {
                       ["coordinates"]=>
                       object(MongoDB\Model\BSONArray)#21 (1) {
                         ["storage":"ArrayObject":private]=>
                         array(2) {
                           [0]=>
                           float(-74.3731727)
                           [1]=>
                           float(40.4404759)
                         }
                       }
                       ["type"]=>
                       string(5) "Point"
                     }
                   }
                   ["name"]=>
                   string(17) "Water'S Edge Club"
                 }
               }
             }
           }
         }
       }
       ["stats"]=>
       object(MongoDB\Model\BSONDocument)#26 (1) {
         ["storage":"ArrayObject":private]=>
         array(5) {
           ["nscanned"]=>
           int(25139)
           ["objectsLoaded"]=>
           int(25134)
           ["avgDistance"]=>
           float(49516.283223281)
           ["maxDistance"]=>
           float(58398.379630263)
           ["time"]=>
           int(126)
         }
       }
       ["ok"]=>
       float(1)
     }
   }

Commands with Custom Read Preference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some commands, such as :manual:`createUser </reference/command/createUser>`, may
only be executed on a :term:`primary` replica set member or a
:term:`standalone`.

The command helper methods in the |php-library|, such as
:phpmethod:`MongoDB\\Database::drop()`, know to apply their own :term:`read
preference` if necessary. However, the :phpmethod:`MongoDB\\Database::command()`
method is a generic method and defaults to the read preference of the Database
object on which it is invoked. To execute commands that require a specific read
preference, specify the read preference in the ``$options`` parameter of the
method.

The following example adds a user to the ``test`` database and specifies a
custom read preference:

.. code-block:: php

   <?php

   $db = (new MongoDB\Client)->test;

   $cursor = $db->command(
       [
           'createUser' => 'username',
           'pwd' => 'password',
           'roles' => ['readWrite'],
       ],
       [
           'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_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)
     }
   }

View Command Results
--------------------

View Single Result Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The :phpmethod:`MongoDB\\Database::command()` method returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object.

Many MongoDB commands return their responses as a single document. To read the
command response, you may either iterate on the cursor and access the first
document, or access the first result in the array, as in the following:

.. code-block:: php

   <?php

   $database = (new MongoDB\Client)->test;

   $cursor = $database->command(['ping' => 1]);

   var_dump($cursor->toArray()[0]);

The output would then resemble::

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

Iterate Results from a Cursor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some commands, such as :manual:`listCollections
</reference/command/listCollections>`, return their results via an iterable
cursor. To view the results, iterate through the cursor.

The following example lists the collections in the ``test`` database by
iterating through the cursor returned by the ``listCollections`` command using a
``foreach`` loop:

.. code-block:: php

   <?php

   $database = (new MongoDB\Client)->test;

   $cursor = $database->command(['listCollections' => 1]);

   foreach ($cursor as $collection) {
       echo $collection['name'], "\n";
   }

The output would then be a list of the values for the ``name`` key, for
instance::

   persons
   posts
   zips

.. note::

   At the *protocol* level, commands that support a cursor return a single
   result document with the essential ingredients for constructing the command
   cursor (i.e. the cursor's ID, namespace, and the first batch of results). In
   the PHP driver implementation, the
   :php:`MongoDB\Driver\Manager::executeCommand()
   <mongodb-driver-manager.executecommand>` method detects such a result and
   constructs the iterable command cursor, which is returned rather than the
   base result document.
