Docs Menu
Docs Home
/ / /
Go Driver

Run a Command

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 Read and Write Settings 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,
...
}
}

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the sample_restaurants database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following example retrieves statistics about the sample_restaurants database:

// Runs a database command by using the Go driver
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
{
db := client.Database("sample_restaurants")
// Retrieves statistics about the specified database
command := bson.D{{"dbStats", 1}}
var result bson.M
// Runs the command and prints the database statistics
err := db.RunCommand(context.TODO(), command).Decode(&result)
// Prints a message if any errors occur during the command execution
if err != nil {
panic(err)
}
/* When you run this file, it should print something similar to the following:
{
"avgObjSize": 548.4101901854896,
"collections": 2,
"dataSize": 14014074,
"db": "sample_restaurants",
"fileSize": 0,
"indexSize": 286720,
"indexes": 2,
"nsSizeMB": 0,
"numExtents": 0,
"objects": 25554,
"ok": 1,
"storageSize": 8257536,
"totalFreeStorageSize": 0,
"views": 0
}
*/
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", output)
}
}
// results truncated
{
"avgObjSize": 548.4101901854896,
"collections": 2,
"dataSize": 14014074,
"db": "sample_restaurants",
"indexSize": 286720,
...,
}

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

Indexes

On this page