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)?
带有mgo驱动程序的MongoDB管理员命令
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
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 theadmin
database. Similarly you will find thatdb.stats()
actually runs thedbstats
command. Thedb.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) } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥15 DruidDataSource一直closing
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
- ¥50 sft下载大文阻塞卡死
- ¥15 机器人轨迹规划相关问题