Run a Command
On this page
Overview
In this guide, you can learn how to use the Rust driver to run a database command. You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.
This guide includes the following sections:
Execute a Command describes the syntax and behavior of the
run_command()
andrun_cursor_command()
methodsResponse describes the information that the command execution methods return
Command Example provides a command example and describes the output for the command
Additional Information provides links to resources and API documentation for types and methods mentioned in this guide
Important
Prefer Driver Methods to Database Commands
The driver provides wrapper methods for many database commands. We recommend using driver methods instead of executing database commands when possible.
To perform administrative tasks, use the MongoDB Shell
instead of the Rust driver. Calling the db.runCommand()
method inside the shell is the preferred way to issue database
commands, as it provides a consistent interface between the shell and
drivers.
Execute a Command
To run a database command, you must specify the command and any relevant parameters in a command document, then pass the command document to a command execution method. The Rust driver provides the following methods to run database commands:
run_command()
, which returns the command response as aDocument
type. You can use this method with any database command.run_cursor_command()
, which returns the command response as an iterableCursor
type. You can use this method only if your database command returns multiple result documents.
The following code shows how you can use the run_command()
method to run the hello
command, which returns information about
the current member's role in the replica set, on a database:
let result = my_db.run_command(doc! { "hello": 1 }).await?;
The checkMetadataConsistency
command returns multiple result
documents. You can use the run_cursor_command()
method to run
this command and collect the results, as shown in the following code:
let cursor = my_db .run_cursor_command(doc! { "checkMetadataConsistency": 1 }) .await?;
To find a link to a full list of database commands and corresponding parameters, see the Additional Information section.
Note
Read Preference
The run_command()
and run_cursor_command()
methods do not
obey the read preference you might have set on your Database
object elsewhere in your code. By default, they use the primary
read preference.
You can set a read preference for command execution by chaining
the selection_criteria()
method to run_command()
or run_cursor_command()
.
The following code shows how to specify a read preference in a
SelectionCriteria
instance and pass it as a parameter to the
selection_criteria()
method:
let result = my_db .run_command(doc! { "hello": 1 }) .selection_criteria(SelectionCriteria::ReadPreference(ReadPreference::Primary)) .await?;
To set a read preference for the run_cursor_command()
method, use the
same syntax as the preceding example.
For more information on read preference options, see Read Preference in the Server manual.
Response
The run_command()
method returns a Document
object that contains
the response from the database after the command has been executed. The
run_cursor_command()
returns a Cursor
that references multiple
result documents.
Each database command performs a different function, so the response content can vary depending on the command executed. However, every response contains a document with the following fields:
Field | Description |
---|---|
<command result> | Fields specific to the database command. For example,
count returns the n field and explain returns the
queryPlanner field. |
ok | Whether the command has succeeded ( 1 )
or failed (0 ). |
operationTime | The logical time of the operation. MongoDB uses the logical time to order operations. To learn more about logical time, see our blog post about the Global Logical Clock. |
$clusterTime | A document that contains the signed cluster time. Cluster time is a logical time used for the ordering of operations. This document contains the following fields:
|
Command Example
The following code shows how you can use the run_command()
method to run
the explain
command for a count
operation on the flowers
collection of the plants
database. The explain
command runs in the
"queryPlanner"
verbosity mode:
let my_db = client.database("plants"); let count_command = doc! { "count": "flowers" }; let explain_command = doc! { "explain": count_command, "verbosity": "queryPlanner" }; let result = my_db.run_command(explain_command).await?;
Output
The output includes fields explaining the
execution of the count
operation, such as the winning plan, which is
the plan selected by the query optimizer, and any rejected
plans. The output also contains information about the execution of the
explain
command:
{ "$clusterTime": { "clusterTime": { "T": 1673969525, "I": 24 }, "signature": {...} }, "command": { "$db": "plants", "count": "flowers" }, "explainVersion": "1", "ok": 1, "operationTime": { "T": 1673969525, "I": 24 }, "queryPlanner": { "indexFilterSet": false, "maxIndexedAndSolutionsReached": false, "maxIndexedOrSolutionsReached": false, "maxScansToExplodeReached": false, "namespace": "plants.flowers", "rejectedPlans": [], "winningPlan": { "stage": "RECORD_STORE_FAST_COUNT" } }, "serverInfo": {...}, "serverParameters": { "internalDocumentSourceGroupMaxMemoryBytes": 104857600, ... } }
Additional Information
For more information about the concepts in this guide, see the following documentation in the Server manual: