Docs Menu

Docs HomeGo Driver

Run a Command

You can run commands directly on your MongoDB server by using the RunCommand() method.


Read the Usage Examples to learn how to run this example.

The following example retrieves statistics about the sample_restaurants database:

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 {

View a fully runnable example

After you run the full example, it returns a SingleResult type that contains the following values:

// results truncated
"avgObjSize": 548.4101901854896,
"collections": 2,
"dataSize": 14014074,
"db": "sample_restaurants",
"indexSize": 286720,


The result variable may vary depending on the contents of your collection.


←  Retrieve Distinct Values of a FieldUse Struct Tags →
Share Feedback