duanqianruan8448 2015-04-09 18:03
浏览 81
已采纳

带有mgo驱动程序的MongoDB管理员命令

Is it possible, given admin creds, to run mongo shell commands such as db.stats(), rs.status() and db.serverStatus() external to the mongo shell via the official Go driver for MongoDB (mgo)?

  • 写回答

2条回答 默认 最新

  • ds78662302 2015-04-10 11:51
    关注

    This is certainly possible, but first you need to bear in mind that the "commands" you have listed are actually shell helpers. You will need to get the real commands that they represent to run them via mgo Session.Run.

    There are a couple of ways to do that, the first is to just run db.listCommands() in the shell and find the appropriate one. The second way to do this is to run the helper you wish to emulate without parentheses. For example:

    > rs.status
    function () { return db._adminCommand("replSetGetStatus"); }
    

    As you can see, what the helper actually does is run the replSetGetStatus command against the admin database. Similarly you will find that db.stats() actually runs the dbstats command. The db.serverStatus() helper is the only one of the three you listed that you can pretty much run as-is.

    Here's a very simple example of running all three - I show two forms of the call, one that just passes a string and the more general option that passes in the full command document - I ran this on a test mongod without auth, so you would have to add that piece yourself to test on an auth-enabled instance:

    package main
    
    import (
        "fmt"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
    )
    
    func main() {
        session, err := mgo.Dial("localhost")
        if err != nil {
            panic(err)
        }
        defer session.Close()
    
        // Optional. Switch the session to a monotonic behavior.
        session.SetMode(mgo.Monotonic, true)
        result := bson.M{}
        if err := session.DB("admin").Run(bson.D{{"serverStatus", 1}}, &result); err != nil {
            panic(err)
        } else {
            fmt.Println(result)
        }
        if err := session.DB("test").Run("dbstats", &result); err != nil {
            panic(err)
        } else {
            fmt.Println(result)
        }
        if err := session.DB("admin").Run("replSetGetStatus", &result); err != nil {
            panic(err)
        } else {
            fmt.Println(result)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集