Docs Menu
Docs Home
/ / /
Go Driver
/

Run a Command

On this page

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

In this guide, you can learn how to run a database command with the Go driver. 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.

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 wrapper method. The command document must be an order-preserving type such as bson.D. The Go driver provides the following methods to run database commands:

  • RunCommand(), which returns the command response as a SingleResult type. You can use this method with any database command.

  • RunCommandCursor(), which returns the command response as a Cursor type. You can use this method if your database command returns multiple result documents.

The following code shows how you can use the RunCommand() method to run the hello command, which returns information about the current member's role in the replica set, on a database:

command := bson.D{{"hello", 1}}
var result bson.M
err = db.RunCommand(context.TODO(), command).Decode(&result)

For a full list of database commands and corresponding parameters, see the Additional Information section.

Note

Read Preference

RunCommand() and RunCommandCursor() do not obey the read preference you may have set on your Database object elsewhere in your code. You can set a read preference for command execution by passing a RunCmdOptions object to either method:

opts := options.RunCmd().SetReadPreference(readpref.Primary())
cursor, err := db.RunCommandCursor(context.TODO(), command, opts)

For more information on read preference options, see the Modify Execution of CRUD Operations fundamentals page.

Each method returns a SingleResult object or a cursor that contains the response from the database after the command has been executed. Each database command performs a different function, so the response content can vary across commands. However, every response contains documents with the following fields:

Field
Description
<command result>
Provides fields specific to the database command. For example, count returns the n field and explain returns the queryPlanner field.
ok
Indicates whether the command has succeeded (1) or failed (0).
operationTime
Indicates 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

Provides a document that returns the signed cluster time. Cluster time is a logical time used for ordering of operations.

The document contains the following fields:

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

  • signature, which is 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 RunCommand() method to run the explain command for a count operation on the flowers collection of the db database. The explain command runs in the "queryPlanner" verbosity mode:

db := client.Database("db")
// Creates commands to count documents in a collection and explain
// how the count command runs
countCommand := bson.D{{"count", "flowers"}}
explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}}
// Retrieves results of the explain command
var result bson.M
err = db.RunCommand(context.TODO(), explainCommand).Decode(&result)

In the output, you should see 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": "db",
"count": "flowers"
},
"explainVersion": "1",
"ok": 1,
"operationTime": {
"T": 1673969525,
"I": 24
},
"queryPlanner": {
"indexFilterSet": false,
"maxIndexedAndSolutionsReached": false,
"maxIndexedOrSolutionsReached": false,
"maxScansToExplodeReached": false,
"namespace": "db.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:

To learn how to retrieve data from a cursor, see the Access Data From a Cursor fundamentals page.

Back

Logging