Skip to content

Commit 4dbf1ca

Browse files
authored
DOCSP-30554: run a command (#9)
1 parent 430d149 commit 4dbf1ca

File tree

4 files changed

+221
-2
lines changed

4 files changed

+221
-2
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use mongodb::{ bson::{ doc, Document }, Client, Database };
2+
3+
#[tokio::main]
4+
async fn main() -> mongodb::error::Result<()> {
5+
let uri: &str = "<connection string>";
6+
7+
let client: Client = Client::with_uri_str(uri).await?;
8+
9+
// start-runcommand
10+
let my_db: Database = client.database("plants");
11+
let count_command: Document = doc! { "count": "flowers" };
12+
let explain_command: Document =
13+
doc! {
14+
"explain": count_command,
15+
"verbosity": "queryPlanner"
16+
};
17+
18+
let result: Document = my_db.run_command(explain_command, None).await?;
19+
// end-runcommand
20+
21+
println!("{}", result);
22+
23+
Ok(())
24+
}

source/fundamentals.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Fundamentals
1010

1111
/fundamentals/connections
1212
/fundamentals/crud
13+
/fundamentals/run-command
1314

1415
..
1516
Connect to MongoDB Atlas from AWS Lambda <https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/>
@@ -22,7 +23,6 @@ Fundamentals
2223
/fundamentals/indexes
2324
/fundamentals/transactions
2425
/fundamentals/logging
25-
/fundamentals/run-command
2626
/fundamentals/collations
2727
/fundamentals/monitoring
2828
/fundamentals/gridfs
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
.. _rust-run-command:
2+
3+
=============
4+
Run a Command
5+
=============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to use the {+driver-short+}
17+
to run a database command. You can use database commands to perform a
18+
variety of administrative and diagnostic tasks, such as fetching server
19+
statistics, initializing a replica set, or running an aggregation pipeline.
20+
21+
.. important:: Prefer Driver Methods to Database Commands
22+
23+
The driver provides wrapper methods for many database commands.
24+
We recommend using driver methods instead of executing database
25+
commands when possible.
26+
27+
To perform administrative tasks, use the :mongosh:`MongoDB Shell </>`
28+
instead of the {+driver-short+}. Calling the ``db.runCommand()``
29+
method inside the shell is the preferred way to issue database
30+
commands, as it provides a consistent interface between the shell and
31+
drivers.
32+
33+
Execute a Command
34+
-----------------
35+
36+
To run a database command, you must specify the command and any relevant
37+
parameters in a command document, then pass the command document to the
38+
``run_command()`` method.
39+
40+
The following code shows how you can use the ``run_command()``
41+
method to run the ``hello`` command, which returns information about
42+
the current member's role in the replica set, on a database:
43+
44+
.. code-block:: rust
45+
46+
let result: Document = my_db.run_command(doc! { "hello": 1 }, None).await?;
47+
48+
For a full list of database commands and corresponding parameters, see
49+
the :ref:`Additional Information section <addl-info-runcommand>`.
50+
51+
.. note:: Read Preference
52+
53+
The ``run_command()`` method does not obey the read preference you
54+
might have set on your ``Database`` object elsewhere in your code. By
55+
default, it uses the ``primary`` read preference.
56+
57+
You can set a read preference for command execution by
58+
passing an options object. The following code shows how to specify a
59+
read preference in a ``SelectionCriteria`` instance and pass it as an
60+
option to the ``run_command()`` method:
61+
62+
.. code-block:: rust
63+
64+
let command_options: SelectionCriteria = SelectionCriteria::ReadPreference(
65+
ReadPreference::Primary
66+
);
67+
let result: Document = my_db.run_command(command_doc, command_options).await?;
68+
69+
For more information on read preference options, see :manual:`Read
70+
Preference </core/read-preference/>` in the Server manual.
71+
72+
Response
73+
--------
74+
75+
The ``run_command()`` method returns a ``Document`` object that contains
76+
the response from the database after the command has been executed. Each
77+
database command performs a different function, so the response content
78+
can vary across commands. However, every response contains a document
79+
with the following fields:
80+
81+
.. list-table::
82+
:header-rows: 1
83+
:widths: 30 70
84+
85+
* - Field
86+
- Description
87+
88+
* - <command result>
89+
- Fields specific to the database command. For example,
90+
``count`` returns the ``n`` field and ``explain`` returns the
91+
``queryPlanner`` field.
92+
93+
* - ``ok``
94+
- Whether the command has succeeded (``1``)
95+
or failed (``0``).
96+
97+
* - ``operationTime``
98+
- The logical time of the operation. MongoDB uses the
99+
logical time to order operations.
100+
101+
.. seealso::
102+
103+
To learn more about logical time, see our blog post about the
104+
:website:`Global Logical Clock </blog/post/transactions-background-part-4-the-global-logical-clock>`.
105+
106+
* - ``$clusterTime``
107+
- A document that contains the signed cluster time. Cluster time is a
108+
logical time used for the ordering of operations.
109+
110+
This document contains the following fields:
111+
112+
- ``clusterTime``, the timestamp of the highest known cluster time for the member
113+
- ``signature``, a document that contains the hash of the cluster time and the ID
114+
of the key used to sign the cluster time
115+
116+
Example
117+
-------
118+
119+
The following code shows how you can use the ``run_command()`` method to run
120+
the ``explain`` command for a ``count`` operation on the ``flowers``
121+
collection of the ``plants`` database. The ``explain`` command runs in the
122+
``"queryPlanner"`` verbosity mode:
123+
124+
.. literalinclude:: /code-snippets/crud/run-command.rs
125+
:language: rust
126+
:dedent:
127+
:start-after: start-runcommand
128+
:end-before: end-runcommand
129+
130+
Output
131+
~~~~~~
132+
133+
The output includes fields explaining the
134+
execution of the ``count`` operation, such as the winning plan, which is
135+
the plan selected by the query optimizer, and any rejected
136+
plans. The output also contains information about the execution of the
137+
``explain`` command:
138+
139+
.. code-block:: json
140+
:emphasize-lines: 9-13,19-29
141+
142+
{
143+
"$clusterTime": {
144+
"clusterTime": {
145+
"T": 1673969525,
146+
"I": 24
147+
},
148+
"signature": {...}
149+
},
150+
"command": {
151+
"$db": "plants",
152+
"count": "flowers"
153+
},
154+
"explainVersion": "1",
155+
"ok": 1,
156+
"operationTime": {
157+
"T": 1673969525,
158+
"I": 24
159+
},
160+
"queryPlanner": {
161+
"indexFilterSet": false,
162+
"maxIndexedAndSolutionsReached": false,
163+
"maxIndexedOrSolutionsReached": false,
164+
"maxScansToExplodeReached": false,
165+
"namespace": "plants.flowers",
166+
"rejectedPlans": [],
167+
"winningPlan": {
168+
"stage": "RECORD_STORE_FAST_COUNT"
169+
}
170+
},
171+
"serverInfo": {...},
172+
"serverParameters": {
173+
"internalDocumentSourceGroupMaxMemoryBytes": 104857600,
174+
...
175+
}
176+
}
177+
178+
.. _addl-info-runcommand:
179+
180+
Additional Information
181+
----------------------
182+
183+
For more information about the concepts in this guide, see the following documentation:
184+
185+
- :manual:`db.runCommand() </reference/method/db.runCommand/>`
186+
- :manual:`Database Commands </reference/command/>`
187+
- :manual:`hello Command </reference/command/hello/>`
188+
- :manual:`explain Command </reference/command/explain/>`
189+
190+
API Documentation
191+
~~~~~~~~~~~~~~~~~
192+
193+
- `run_command() <{+api+}/struct.Database.html#method.run_command>`__
194+
- `SelectionCriteria <{+api+}/options/enum.SelectionCriteria.html>`__
195+
- `ReadPreference <{+api+}/options/enum.ReadPreference.html>`__

source/includes/fundamentals-sections.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ Fundamentals section:
33

44
- :ref:`Connect to MongoDB <rust-connection>`
55
- :ref:`Read from and Write to MongoDB <rust-crud>`
6+
- :ref:`Run A Database Command <rust-run-command>`
67

78
..
89
- :atlas:`Connect to MongoDB Atlas from AWS Lambda </manage-connections-aws-lambda/>`
@@ -14,7 +15,6 @@ Fundamentals section:
1415
- :ref:`Construct Indexes <rust-indexes>`
1516
- :ref:`Specify Collations to Order Results <rust-collations>`
1617
- :ref:`Record Log Messages <rust-logging>`
17-
- :ref:`Run A Database Command <rust-run-command>`
1818
- :ref:`Monitor Driver Events <rust-monitoring>`
1919
- :ref:`Store and Retrieve Large Files by Using GridFS <rust-gridfs>`
2020
- :ref:`Use a Time Series Collection <rust-time-series>`

0 commit comments

Comments
 (0)