Docs Menu

コマンドの実行

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.

重要

データベースコマンドよりもドライバー メソッドを優先

このドライバーは、多くのデータベース コマンドのラッパー メソッドを提供します。 可能な場合は、データベースコマンドを実行する代わりにドライバー メソッドを使用することをお勧めします。

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 データベース コマンド 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)

読み込み設定(read preference)オプションの詳細については、サーバー マニュアルの読み込み設定(read preference) を参照してください。

注意

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.

runCommand() メソッドは、コマンド実行後のデータベースからの応答を含む Documentオブジェクトを返します。 各データベースコマンドは異なる機能を実行するため、応答内容はコマンド間で異なる可能性があります。 ただし、すべての応答には次のフィールドを持つドキュメントが含まれます。

フィールド
説明

<command result=""></command>

データベースコマンド に固有のフィールドを提供します。 たとえば、 countnフィールドを返し、 explainqueryPlannerフィールドを返します。

ok

コマンドが成功(1)したか失敗(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

署名されたクラスター時間を返すドキュメントを提供します。 クラスター時間は、操作の順序付けに使用される論理時間です。

このドキュメントには、以下のフィールドが含まれています。

  • clusterTimeは、ノードの最も高い既知のクラスター時間のタイムスタンプです。

  • signatureは、クラスター時間のハッシュと、クラスター時間に署名するために使用されるキーの ID を含むドキュメントです。

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({ ... })
}

このガイドの概念の詳細については、次のドキュメントを参照してください。