Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo - how to get status as a python dictionary for rep sets

I am new to mongo and I am using pymongo. I am finding the documentation for pymongo to be all over the place.

1) I have a rep set. From the mongo shell, if I run the below I get what I need.

sudo mongo 111.111.111.111 --eval "printjson(rs.status())"
MongoDB shell version: 2.2.1
connecting to: 111.111.111.111/test
{
    "set" : "hey",
    "date" : ISODate("2012-11-10T11:47:58Z"),
    "myState" : 1,
    "members" : [
        {
            "_id" : 0,
            "name" : "111.111.111.111:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 69189,
            "optime" : Timestamp(1352478921000, 1),
            "optimeDate" : ISODate("2012-11-09T16:35:21Z"),
            "self" : true
        }
    ],
    "ok" : 1
}

I need to get that info from pymongo.

1) I connect to the primary. I get none but per the above that node is primary:

c = ReplicaSetConnection("111.111.111.111:27017", replicaSet='heythat')
print c.primary
None

2) I want to run c.command("status") but that operation is not supported.

So, how to I use pymongo to return the primary and also to return status as a Python dictionary?

like image 488
Tampa Avatar asked Nov 10 '12 12:11

Tampa


1 Answers

rs.status() calls the 'replSetGetStatus' admin command, in python you can do that like so:

conn = ReplicaSetConnection("111.111.111.111:27017", replicaSet='heythat')
conn.admin.command('replSetGetStatus')

Protip: If you want to know what command a shell helper calls, then leave the brackets off the function to see the code eg:

heythat:PRIMARY> rs.status
function () {
    return db._adminCommand("replSetGetStatus");
}
like image 62
Ross Avatar answered Nov 11 '22 21:11

Ross