golang 获取 mongo 数据库状态

命令行模式

golang

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var ctx = context.TODO()

func main() {
	clientOptions := options.Client().ApplyURI("mongodb://root:123456@localhost:27017/")
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}

	database := client.Database("admin")
	result := bson.M{}
	cmd := bson.D{{Key: "dbStats", Value: 1}}
	err = database.RunCommand(ctx, cmd).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}

	jsonResult, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(jsonResult))
}

python

from pymongo import MongoClient


if __name__ == '__main__':

    # 连接MongoDB数据库
    client = MongoClient("mongodb://root:123456@localhost:27017")

    # 获取数据库状态
    db = client.admin
    result = db.command("dbStats")

    # 打印数据库状态信息
    print("Database Status:")
    for key, value in result.items():
        print(f"{key}: {value}")

posted @ 2023-10-26 15:13  vx_guanchaoguo0  阅读(28)  评论(0编辑  收藏  举报