Search code examples
mongodbpymongoreplicaset

How to use Pymongo to manage Replicaset


this is my question. I need to check that the Mongo cluster was created successfully. In general, use the rs.status() command. But this requires me to manually enter the Mongo command panel, which is not friendly for a lazy person. So I want to use Pymongo to implement the rs.status() command. So if you know how to implement rs.status() with Pymongo or some other better way to check for cluster success, please let me know in the first place. Thank you.


Solution

  • db.command allows low level access to the mongodb commands. To get the replica set status, it's replSetGetStatus.

    from pymongo import MongoClient
    
    # NB Must be a replica set
    # Must be connected to the admin database
    db = MongoClient()['admin']
    
    rs_status = db.command({'replSetGetStatus': 1})
    print(rs_status)