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条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制