Skip to content

Commit ef92229

Browse files
committed
DOCSP-41956: run a command
1 parent 855563c commit ef92229

File tree

2 files changed

+198
-0
lines changed

2 files changed

+198
-0
lines changed

source/includes/write/run-command.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
require __DIR__ . '/vendor/autoload.php';
4+
5+
use MongoDB\Client;
6+
7+
$client = new Client('<connection string>');
8+
9+
// start-runcommand
10+
$database = $client->plants;
11+
12+
$countCommand = ['count' => 'flowers'];
13+
$explainCommand = ['explain' => $countCommand, 'verbosity' => 'queryPlanner'];
14+
15+
$result = $database->command($explainCommand);
16+
// end-runcommand
17+
18+
var_dump($result->toArray());
19+

source/write/run-command.txt

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
.. _php-run-command:
2+
3+
======================
4+
Run a Database Command
5+
======================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: administration, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+php-library+}
24+
to run a database command. You can use database commands to perform a
25+
variety of administrative and diagnostic tasks, such as fetching server
26+
statistics, initializing a replica set, or running an aggregation pipeline.
27+
28+
.. important:: Prefer Library Methods to Database Commands
29+
30+
The library provides wrapper methods for many database commands.
31+
We recommend using these methods instead of executing database
32+
commands when possible.
33+
34+
To perform administrative tasks, use the :mongosh:`MongoDB Shell </>`
35+
instead of the {+php-library+}. Calling the ``db.runCommand()``
36+
method inside the shell is the preferred way to issue database
37+
commands, as it provides a consistent interface between the shell and
38+
drivers or libraries.
39+
40+
.. _php-execute-command:
41+
42+
Execute a Command
43+
-----------------
44+
45+
To run a database command, you must specify the command and any relevant
46+
parameters in a command document, then pass the command document to the
47+
``command()`` method. This method returns a ``Cursor`` object.
48+
49+
The following code shows how you can use the ``command()``
50+
method to run the ``hello`` command, which returns information about
51+
the current member's role in the replica set, on a database:
52+
53+
.. code-block:: php
54+
55+
$result = $database->command(['ping' => 1]);
56+
57+
To find a link to a full list of database commands and corresponding
58+
parameters, see the :ref:`Additional Information section
59+
<php-addtl-info-runcommand>`.
60+
61+
.. note:: Read Preference
62+
63+
The ``command()`` method does not
64+
obey the read preference you might have set on your ``Database``
65+
instance elsewhere in your code. By default, ``command()`` uses the ``primary``
66+
read preference.
67+
68+
You can set a read preference for command execution by setting one
69+
in the options parameter, as shown in the following code:
70+
71+
.. code-block:: php
72+
73+
$readPref = new MongoDB\Driver\ReadPreference('primaryPreferred');
74+
$result = $database->command(['ping' => 1], ['readPreference' => $readPref]);
75+
76+
For more information on read preference options, see :manual:`Read
77+
Preference </core/read-preference/>` in the Server manual.
78+
79+
.. _php-command-response:
80+
81+
Response
82+
--------
83+
84+
The ``command()`` method returns a ``Cursor`` object that contains
85+
the response from the database after the command has been executed.
86+
87+
Each database command performs a different function, so the response
88+
content can vary depending on the command executed. However, every
89+
response contains a document with the following fields:
90+
91+
.. list-table::
92+
:header-rows: 1
93+
:widths: 30 70
94+
95+
* - Field
96+
- Description
97+
98+
* - <command result>
99+
- Fields specific to the database command. For example,
100+
``count`` returns the ``n`` field and ``explain`` returns the
101+
``queryPlanner`` field.
102+
103+
* - ``ok``
104+
- Whether the command has succeeded (``1``)
105+
or failed (``0``).
106+
107+
* - ``operationTime``
108+
- The logical time of the operation. MongoDB uses the
109+
logical time to order operations.
110+
111+
.. seealso::
112+
113+
To learn more about logical time, see our blog post about the
114+
:website:`Global Logical Clock </blog/post/transactions-background-part-4-the-global-logical-clock>`.
115+
116+
* - ``$clusterTime``
117+
- A document that contains the signed cluster time. Cluster time is a
118+
logical time used for the ordering of operations.
119+
120+
This document contains the following fields:
121+
122+
- ``clusterTime``, the timestamp of the highest known cluster time for the member
123+
- ``signature``, a document that contains the hash of the cluster time and the ID
124+
of the key used to sign the cluster time
125+
126+
.. _rust-command-example:
127+
128+
Command Example
129+
---------------
130+
131+
The following code shows how you can use the ``command()`` method to run
132+
the ``explain`` command for a ``count`` operation on the ``flowers``
133+
collection of the ``plants`` database. The ``explain`` command runs in the
134+
``"queryPlanner"`` verbosity mode:
135+
136+
.. literalinclude:: /includes/write/run-command.php
137+
:language: php
138+
:dedent:
139+
:start-after: start-runcommand
140+
:end-before: end-runcommand
141+
142+
Output
143+
~~~~~~
144+
145+
The output includes fields explaining the
146+
execution of the ``count`` operation, such as the winning plan, which is
147+
the plan selected by the query optimizer, and any rejected
148+
plans. The output also contains information about the execution of the
149+
``explain`` command:
150+
151+
.. code-block:: json
152+
:emphasize-lines:
153+
154+
string(1203)
155+
"[{"explainVersion":"1","queryPlanner":{"namespace":"plants.flowers",
156+
"indexFilterSet":false,"maxIndexedOrSolutionsReached":false,
157+
"maxIndexedAndSolutionsReached":false,"maxScansToExplodeReached":false,"winningPlan":
158+
{"stage":"RECORD_STORE_FAST_COUNT"},"rejectedPlans":[]},"command":{"count":"flowers",
159+
"$db":"plants"},"serverInfo":{"host":"...","port":27017,"version":"7.0.12",
160+
"gitVersion":"..."},"serverParameters":{...},"ok":1,"$clusterTime":{...},"signature":{...},
161+
"keyId":...}},"operationTime":{"$timestamp":{"t":1725637892,"i":12}}}]"
162+
163+
.. _php-addtl-info-runcommand:
164+
165+
Additional Information
166+
----------------------
167+
168+
For more information about the concepts in this guide, see the following
169+
documentation in the Server manual:
170+
171+
- :manual:`db.runCommand() </reference/method/db.runCommand/>`
172+
- :manual:`Database Commands </reference/command/>`
173+
- :manual:`hello Command </reference/command/hello/>`
174+
- :manual:`explain Command </reference/command/explain/>`
175+
176+
API Documentation
177+
~~~~~~~~~~~~~~~~~
178+
179+
- `MongoDB\\Database::command() <{+api+}/method/MongoDBDatabase-command/>`__

0 commit comments

Comments
 (0)