AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

データベースコマンドの実行

このガイドでは、Go ドライバーを使用してデータベースコマンドを実行する方法を学習できます。 データベースコマンドを使用して、サーバー統計の取得、レプリカセットの初期化、集計パイプラインの実行など、さまざまな管理および診断タスクを実行できます。

データベースコマンドを実行するには、コマンドとコマンド ドキュメントでコマンドと関連するパラメーターを指定し、そのコマンド ドキュメントをラッパー メソッドに渡す必要があります。 コマンド ドキュメントは、 bson.Dなどの順序保持タイプである必要があります。 Go ドライバーは、データベースコマンドを実行するための次のメソッドを提供します。

  • RunCommand()は、コマンドの応答をSingleResultタイプとして返します。 このメソッドは任意のデータベースコマンドで使用できます。

  • RunCommandCursor()は、コマンドの応答をCursorタイプとして返します。 データベースコマンドが複数の結果ドキュメントを返す場合は、このメソッドを使用できます。

次のコードは、 RunCommand()メソッドを使用してデータベース上でレプリカセット内の現在のノードのロールに関する情報を返すhelloコマンドを実行する方法を示しています。

command := bson.D{{"hello", 1}} var result bson.Merr = db.RunCommand(context.TODO(), command).Decode(&result)

データベースコマンドと対応するパラメータの完全なリストについては、「追加情報 」セクションを参照してください。

注意

読み込み設定 (read preference)

RunCommand() とRunCommandCursor()は、コード内の他の場所にあるDatabaseオブジェクトに設定した読み取り設定に従いません。 You can set a read preference for command execution by passing a RunCmdOptions object to either method:

opts := options.RunCmd().SetReadPreference(readpref.Primary())cursor, err := db.RunCommandCursor(context.TODO(), command, opts)

読み込み設定(読み込み設定 (read preference)オプションの詳細については、「 読み取り設定と書込み設定 」を参照してください。

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

フィールド
説明

<command result>

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

ok

コマンドが成功(1)したか失敗(0)したかを示します。

operationTime

操作の論理時間を示します。 MongoDBは論理時間を使用して操作を順序付けます。 論理時間の詳細については、 グローバル論理クロック に関するブログ記事をご覧ください。

$clusterTime

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

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

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

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

次のコードは、 RunCommand()メソッドを使用して、 dbデータベースのflowersコレクションに対してcount操作を行うためのexplainコマンドを実行する方法を示しています。 explainコマンドは"queryPlanner"の冗長モードで実行されます。

db := client.Database("db") // Creates commands to count documents in a collection and explain// how the count command runscountCommand := bson.D{{"count", "flowers"}}explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}} // Retrieves results of the explain commandvar result bson.Merr = db.RunCommand(context.TODO(), explainCommand).Decode(&result)

出力には、 クエリオプティマイザ によって選択されたプランである勝利プランや拒否されたプランなど、 count操作の実行を説明するフィールドが表示されます。 出力には、 explainコマンドの実行に関する情報も含まれています。

{ "$clusterTime": { "clusterTime": { "T": 1673969525, "I": 24 }, "signature": {...} }, "command": { "$db": "db", "count": "flowers" }, "explainVersion": "1", "ok": 1, "operationTime": { "T": 1673969525, "I": 24 }, "queryPlanner": { "indexFilterSet": false, "maxIndexedAndSolutionsReached": false, "maxIndexedOrSolutionsReached": false, "maxScansToExplodeReached": false, "namespace": "db.flowers", "rejectedPlans": [], "winningPlan": { "stage": "RECORD_STORE_FAST_COUNT" } }, "serverInfo": {...}, "serverParameters": { "internalDocumentSourceGroupMaxMemoryBytes": 104857600, ... }}

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」を参照してください。この例でも、Atlas サンプル データセットに含まれる sample_restaurants データベースを使用します。Atlas スタートガイドの手順に従って、MongoDB Atlas の無料クラスター上のデータベースにロードできます。

次の例では、 sample_restaurantsデータベースに関する統計を取得します。

// Runs a database command by using the Go driverpackage main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options") func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ja-jp/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() { db := client.Database("sample_restaurants") // Retrieves statistics about the specified database command := bson.D{{"dbStats", 1}} var result bson.M // Runs the command and prints the database statistics err := db.RunCommand(context.TODO(), command).Decode(&result) // Prints a message if any errors occur during the command execution if err != nil { panic(err) } /* When you run this file, it should print something similar to the following: { "avgObjSize": 548.4101901854896, "collections": 2, "dataSize": 14014074, "db": "sample_restaurants", "fileSize": 0, "indexSize": 286720, "indexes": 2, "nsSizeMB": 0, "numExtents": 0, "objects": 25554, "ok": 1, "storageSize": 8257536, "totalFreeStorageSize": 0, "views": 0 } */ output, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output) }}

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

カーソルからデータを検索する方法については、「 カーソルからデータにアクセスする」の基礎ページを参照してください。