Docs Menu
Docs Home
/ / /
C#/.NET
/ /

Run a Database Command

On this page

  • Overview
  • Sample Data
  • Execute a Command
  • Set a Read Preference
  • Response
  • Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the .NET/C# 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.

Important

Prefer Driver Methods to Database Commands

The driver provides wrapper methods for many database commands. If possible, we recommend using these methods instead of executing database commands.

To perform administrative tasks, use the MongoDB Shell instead of the .NET/C# Driver. The shell provides helper methods that might not be available in the driver.

If there are no available helpers in the driver or the shell, you can use the db.runCommand() shell method or the driver's RunCommand() and RunCommandAsync() methods, which are described in this guide.

The examples in this guide use the sample_restaurants.restaurants collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Quick Start.

To run a database command, create a BsonDocument object that specifies the command and pass it as a parameter to the RunCommand() or RunCommandAsync() method. You can specify the type returned by these methods by specifying the type parameter. You can use the BsonDocument type to return the command response, or you can specify your own strongly typed class to deserialize the command response.

The following example runs the hello command on a database, which returns information about the server. Select the Asynchronous or Synchronous tab to see the corresponding code.

var command = new BsonDocument("hello", 1);
var result = await database.RunCommandAsync<BsonDocument>(command);
var command = new BsonDocument("hello", 1);
var result = database.RunCommand<BsonDocument>(command);

Tip

To view a full list of database commands and their corresponding parameters, see Database Commands in the MongoDB Server manual.

The RunCommand() method does not inherit the read preference you might have set on your MongoDatabase instance. By default, RunCommand() uses the primary read preference.

You can set a read preference for the command execution by passing a ReadPreference instance as a parameter to RunCommand(), as shown in the following example. Select the Asynchronous or Synchronous tab to see the corresponding code.

var command = new BsonDocument("hello", 1);
var result = await database.RunCommandAsync<BsonDocument>(command, ReadPreference.Secondary);
var command = new BsonDocument("hello", 1);
var result = database.RunCommand<BsonDocument>(command, ReadPreference.Secondary);

Tip

To learn more about read preference options, see Read Preference in the MongoDB Server manual.

The raw command response document returned by the RunCommand() method contains the following fields:

Field
Description

<command result>

Fields specific to the database command. For example, the hello command returns the topologyVersion field.

ok

Indicates whether the command has succeeded (1.0) or failed (0.0). The driver raises a MongoCommandException if the ok value is 0.0.

$clusterTime

A document that contains the signed cluster time. Cluster time is a logical time used for the ordering of operations. This field only applies to commands run on replica sets or sharded clusters.

operationTime

The logical time of the operation execution. This field only applies to commands run on replica sets or sharded clusters.

The following example runs the dbStats command to retrieve storage statistics for the sample_restaurants database, then prints the command results by using the ToJson() method on the returned BsonDocument object. Select the Asynchronous or Synchronous tab to see the corresponding code.

var command = new BsonDocument("dbStats", 1);
var result = await database.RunCommandAsync<BsonDocument>(command);
Console.WriteLine(result.ToJson());
var command = new BsonDocument("dbStats", 1);
var result = database.RunCommand<BsonDocument>(command);
Console.WriteLine(result.ToJson());

The output of this command includes information about the data stored in the database, as shown in the result returned by the previous example:

{ "db" : "sample_restaurants", "collections" : 2, "views" : 0, "objects" :
NumberLong(25438), "avgObjSize" : 548.95172576460413, "dataSize" : NumberLong(13964234),
"storageSize" : NumberLong(8056832), "totalFreeStorageSize" : NumberLong(0),
"numExtents" : NumberLong(0), "indexes" : 2, "indexSize" : NumberLong(1044480),
"indexFreeStorageSize" : NumberLong(0), "fileSize" : NumberLong(0), "nsSizeMB" : 0, "ok" : 1 }

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

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Databases & Collections