1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
116
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
155
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
=========================
Execute Database Commands
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
The |php-library| provides :ref:`helper methods <database-methods>`
for common :manual:`database commands </reference/command>`. In
addition, the |php-library| provides the
:phpmethod:`MongoDB\\Database::command` method to run database commands
with PHP that do not have helper methods.
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 :dbcommand:`geoNear` HERE command to search for
the three closest documents to longitude ``-74`` and latitude ``40`` in
the ``restos`` collection in the ``example`` database:
:readmode:`secondary`
.. code-block:: php
<?php
$database = (new MongoDB\Client)->example;
$results = $database->command(
[
'geoNear' => 'restos',
'near' => [
'type' => 'Point',
'coordinates' => [-74.0, 40.0]
],
'spherical' => 'true',
'num' => 3
]
);
var_dump($results);
The output would resemble::
object(MongoDB\Driver\Cursor)#10 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#3 (4) {
["geoNear"]=>
string(6) "restos"
["near"]=>
object(stdClass)#9 (2) {
["type"]=>
string(5) "Point"
["coordinates"]=>
array(2) {
[0]=>
float(-74)
[1]=>
float(40)
}
}
["spherical"]=>
string(4) "true"
["num"]=>
int(3)
}
["fields"]=>
object(stdClass)#8 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#24 (4) {
["waitedMS"]=>
int(0)
["results"]=>
array(3) {
[0]=>
object(stdClass)#14 (2) {
["dis"]=>
float(66308.6190421)
["obj"]=>
object(stdClass)#13 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd28"
}
["name"]=>
string(21) "XYZ Bagels Restaurant"
["contact"]=>
object(stdClass)#12 (3) {
["phone"]=>
string(12) "435-555-0190"
["email"]=>
string(31) "XYZBagelsRestaurant@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0707363)
[1]=>
float(40.5932157)
}
}
["stars"]=>
int(4)
["categories"]=>
array(3) {
[0]=>
string(6) "Bagels"
[1]=>
string(10) "Sandwiches"
[2]=>
string(6) "Coffee"
}
}
}
[1]=>
object(stdClass)#18 (2) {
["dis"]=>
float(69014.6014737)
["obj"]=>
object(stdClass)#17 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd39"
}
["name"]=>
string(20) "Green Feast Pizzeria"
["contact"]=>
object(stdClass)#16 (3) {
["phone"]=>
string(12) "840-555-0102"
["email"]=>
string(30) "GreenFeastPizzeria@example.com"
["location"]=>
array(2) {
[0]=>
float(-74.1220973)
[1]=>
float(40.6129407)
}
}
["stars"]=>
int(2)
["categories"]=>
array(2) {
[0]=>
string(5) "Pizza"
[1]=>
string(7) "Italian"
}
}
}
[2]=>
object(stdClass)#22 (2) {
["dis"]=>
float(69975.5031089)
["obj"]=>
object(stdClass)#21 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#19 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd35"
}
["name"]=>
string(14) "XYZ Coffee Bar"
["contact"]=>
object(stdClass)#20 (3) {
["phone"]=>
string(12) "644-555-0193"
["email"]=>
string(24) "XYZCoffeeBar@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0166091)
[1]=>
float(40.6284767)
}
}
["stars"]=>
int(5)
["categories"]=>
array(4) {
[0]=>
string(6) "Coffee"
[1]=>
string(4) "Cafe"
[2]=>
string(6) "Bakery"
[3]=>
string(10) "Chocolates"
}
}
}
}
["stats"]=>
object(stdClass)#23 (5) {
["nscanned"]=>
int(11)
["objectsLoaded"]=>
int(10)
["avgDistance"]=>
float(68432.9078749)
["maxDistance"]=>
float(69975.5031089)
["time"]=>
int(0)
}
["ok"]=>
float(1)
}
}
["server_id"]=>
int(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
specific read preference, specify the read preference in the ``$options``
parameter of the method.
The following example adds a user to the ``demo`` database
and specifies a custom read preference:
.. code-block:: php
<?php
$db = (new MongoDB\Client)->demo;
$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 in an
array. 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)->demo;
$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 ``demo`` database by
iterating through the cursor returned by the ``listCollections`` command
using a ``foreach`` loop:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->demo;
$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:`executeCommand() <mongodb-driver-manager.executecommand>`
method detects the single result and constructs the iterable command
cursor, which is returned rather than the base result document.