sdot257
sdot257

Reputation: 10366

How to set connection timeout for Mongodb using pymongo?

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>

Upvotes: 33

Views: 28713

Answers (2)

Ben Slade
Ben Slade

Reputation: 508

The web page: https://api.mongodb.com/python/current/api/pymongo/mongo_client.html says:

connectTimeoutMS: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to 20000 (20 seconds)

(Where "server monitoring" is undefined)

So what? Is connectTimeoutMS sort of like a decoy to keep out the amateurs (like me)

Upvotes: 4

sdot257
sdot257

Reputation: 10366

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

What I was looking for is serverSelectionTimeoutMS

Upvotes: 48

Related Questions