Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go Driver

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

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

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

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

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

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

command := bson.D{{"hello", 1}}
var result bson.M
err = 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>

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

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 runs
countCommand := bson.D{{"count", "flowers"}}
explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}}
// Retrieves results of the explain command
var result bson.M
err = 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 driver
package 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)
}
}
// results truncated
{
"avgObjSize": 548.4101901854896,
"collections": 2,
"dataSize": 14014074,
"db": "sample_restaurants",
"indexSize": 286720,
...,
}

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

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

戻る

Indexes

項目一覧