commands.txt 9.71 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
=========================
Execute Database Commands
=========================

.. default-domain:: mongodb

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

Overview
--------

16 17 18 19 20 21
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.
22 23 24 25 26 27 28 29

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

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

To execute a command on a :program:`mongod` instance, use the
30 31 32
: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``
33
in the ``restos`` collection in the ``test`` database:
34 35 36 37 38

.. code-block:: php

   <?php

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

41 42 43 44 45 46 47 48 49 50 51
   $cursor = $database->command([
       'geoNear' => 'restos',
       'near' => [
           'type' => 'Point',
           'coordinates' => [-74.0, 40.0],
       ],
       'spherical' => 'true',
       'num' => 3,
   ]);

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

   var_dump($results);

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
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"]=>
77
                   object(MongoDB\BSON\ObjectId)#3 (1) {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
                     ["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"]=>
116
                   object(MongoDB\BSON\ObjectId)#15 (1) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
                     ["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"]=>
155
                   object(MongoDB\BSON\ObjectId)#20 (1) {
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
                     ["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
207 208
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

213 214 215 216 217 218 219
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.
220

221
The following example adds a user to the ``test`` database and specifies a
222
custom read preference:
223 224 225 226 227

.. code-block:: php

   <?php

228
   $db = (new MongoDB\Client)->test;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

   $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
260
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object.
261

262 263 264
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:
265 266 267 268 269

.. code-block:: php

   <?php

270
   $database = (new MongoDB\Client)->test;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

   $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
290
</reference/command/listCollections>`, return their results via an iterable
291
cursor. To view the results, iterate through the cursor.
292

293
The following example lists the collections in the ``test`` database by
294 295
iterating through the cursor returned by the ``listCollections`` command using a
``foreach`` loop:
296 297 298 299 300

.. code-block:: php

   <?php

301
   $database = (new MongoDB\Client)->test;
302 303 304 305 306 307 308

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

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

309 310
The output would then be a list of the values for the ``name`` key, for
instance::
311 312 313 314 315 316 317

   persons
   posts
   zips

.. note::

318 319 320 321 322 323 324 325
   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.