Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversKotlin Coroutine

Run a Command

You can run all raw database operations using the MongoDatabase.runCommand() method. A raw database operation is a command you can execute directly on the MongoDB server CLI. These commands include administrative and diagnostic tasks, such as fetching server stats or initializing a replica set. Call the runCommand() method with a Bson command object on an instance of a MongoDatabase to run your raw database operation.

Tip

Use the MongoDB Shell for administrative tasks instead of the Kotlin driver whenever possible, since these tasks are often quicker and easier to implement with the shell than in a Kotlin application.

The runCommand() method accepts a command in the form of a Bson object. By default, runCommand returns an object of type org.bson.Document containing the output of the database command. You can specify a return type for runCommand() as an optional second parameter.

In the following sample code, we send the dbStats command to request statistics from a specific MongoDB database.

Note

This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

import com.mongodb.MongoException
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.BsonDocument
import org.bson.BsonInt64
import org.bson.json.JsonWriterSettings
fun main() = runBlocking {
// Replace the uri string 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 = BsonDocument("dbStats", 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()
}

For additional information on the classes and methods mentioned on this page, see the following resources:

←  Retrieve Distinct Values of a FieldFundamentals →