Docs Menu

Run a Command

In this guide, you can learn how to run a database command by using the Kotlin Sync 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.

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 Kotlin Sync driver. Calling the db.runCommand() method inside the shell is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.

To run a database command, specify the command and any relevant parameters in a document, then pass the document to the runCommand() method.

The following code shows how you can use the runCommand() method to run the explain command, which returns a description of how the find command will be executed if you call it:

val commandToExplain = Document("find", "restaurants")
val explanation = database.runCommand(Document("explain", commandToExplain))

For a full list of database commands and corresponding parameters, see the Database Commands guide.

You can specify optional command behavior for the runCommand() method by including a readPreference parameter. The following example shows how to specify a read preference and pass it as an option to the runCommand() method:

val command = Document("hello", 1)
val commandReadPreference = Document("readPreference", "secondary")
val commandResult = database.runCommand(command, commandReadPreference)

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

Note

The runCommand() method ignores the read preference setting you may have set on your database object. If no read preference is specified, this method uses the primary read preference.

The runCommand() method returns a Document object 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 example shows how to run the buildInfo command, and the output it produces:

import com.mongodb.MongoException
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import org.bson.BsonInt64
import org.bson.json.JsonWriterSettings
fun main() {
// Replace the placeholder with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
try {
val command = Document("buildInfo", BsonInt64(1))
val commandResult = database.runCommand(command)
println(commandResult.toJson(JsonWriterSettings.builder().indent(true).build()))
} catch (me: MongoException) {
System.err.println("An error occurred: $me")
}
mongoClient.close()
}
{
version: '8.0.4',
...<other command results>...
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ ... }),
signature: {
...
}
},
operationTime: Timestamp({ ... })
}

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