go - MongoDB admin commands with mgo driver -
is possible, given admin creds, run mongo shell commands such db.stats()
, rs.status()
, db.serverstatus()
external mongo shell via official go driver mongodb (mgo)?
this possible, first need bear in mind "commands" have listed shell helpers. need real commands represent run them via mgo
session.run.
there couple of ways that, first run db.listcommands()
in shell , find appropriate one. second way run helper wish emulate without parentheses. example:
> rs.status function () { return db._admincommand("replsetgetstatus"); }
as can see, helper run replsetgetstatus
command against admin
database. find db.stats()
runs dbstats
command. db.serverstatus()
helper 1 of 3 listed can pretty run as-is.
here's simple example of running 3 - show 2 forms of call, 1 passes string , more general option passes in full command document - ran on test mongod
without auth, have add piece test on 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 session 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) } }