For monitoring purposees I try to get the output of the following shell commands but from a python script
:mongo --port 27040
-> enters mongodb shell
:rs.status()
The result of the command is json that I want to access outside the mongo shell to write it to a file, I can run other command in python using pymongo like:
import json, os
# load mongo library
current_dir = os.path.dirname(os.path.realpath(__file__))
os.sys.path.append(os.path.join(current_dir, 'pymongo-3.7.1-cp27-cp27m-manylinux1_x86_64.whl'))
from bson import json_util
from pymongo import MongoClient
from pymongo.errors import OperationFailure, ConnectionFailure
#connection settings
port = 27040
hostname = "localhost"
#default database used by mongodb
database = "test"
try:
# connect to the database
client = MongoClient(hostname,int(port))
db = client[database] # select the database
serverstats = db.command("serverStatus")
serialized_serverstats = json.dumps(serverstats, default=json_util.default)
print serialized_serverstats
except Exception as e:
print("Unhandled Error is %s" % e)
This runs something equal to running db.serverStatus() in the mongo shell. But how do I run rs.status() form inside a python script?
You should do it like this:
db = client ['admin']
db_stats = db.command({'replSetGetStatus' :1})
If you want to check what's the underlying command of any shell command:
> rs.status
function () {
return db._adminCommand("replSetGetStatus");
}
>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.