How to set connection timeout for Mongodb using pymongo?

luckytaxi picture luckytaxi · Sep 2, 2016 · Viewed 9.5k times · Source

I tried setting connectTimeoutMS and socketTimeoutMS to a low value but it still takes about 20 seconds before my script times out. Am I not using the options correctly? I want the script to exit after 5 seconds.

def init_mongo():
    mongo_connection = MongoClient('%s' %MONGO_SERVER, connectTimeoutMS=5000, socketTimeoutMS=5000)
    if mongo_connection is None:
        return

    try:
        <code>
    except:
        <code>

Answer

luckytaxi picture luckytaxi · Sep 2, 2016

So if anyone comes across this later, I was using the wrong option.

What I was looking for is serverSelectionTimeoutMS