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)?
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With