Docs Menu
Docs Home
/ / /
Rust Driver
/

Run a Command

On this page

  • Overview
  • Execute a Command
  • Response
  • Command Example
  • Output
  • Additional Information
  • API Documentation

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() and run_cursor_command() methods

  • Response 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.

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 a Document type. You can use this method with any database command.

  • run_cursor_command(), which returns the command response as an iterable Cursor 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 }, None).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 }, None)
.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 passing an options object to either method. The following code shows how to specify a read preference in a SelectionCriteria instance and pass it as an option to the run_command() method:

let command_options = SelectionCriteria::ReadPreference(
ReadPreference::Primary
);
let result = my_db.run_command(command_doc, command_options).await?;

The run_cursor_command() method takes a RunCursorCommandOptions instance as a parameter. You can set the selection_criteria field of this struct to select a read preference.

For more information on read preference options, see Read Preference in the Server manual.

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.

Tip

See also:

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:

  • clusterTime, the timestamp of the highest known cluster time for the member

  • signature, a document that contains the hash of the cluster time and the ID of the key used to sign the cluster time

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, None).await?;

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,
...
}
}

For more information about the concepts in this guide, see the following documentation in the Server manual:

← Tracing & Logging