Docs Menu
Docs Home
/ / /
Kotlin 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()
}
{
"db": "sample_mflix",
"collections": 5,
"views": 0,
"objects": 75595,
"avgObjSize": 692.1003770090614,
"dataSize": 52319328,
"storageSize": 29831168,
"numExtents": 0,
"indexes": 9,
"indexSize": 14430208,
"fileSize": 0,
"nsSizeMB": 0,
"ok": 1
}

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

  • runCommand() API Documentation

  • Database Commands Server Manual Entry

  • dbStats Server Manual Entry

Back

Retrieve Distinct Values of a Field