Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set connection timeout for Mongodb using pymongo?

Tags:

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> 
like image 271
sdot257 Avatar asked Sep 02 '16 17:09

sdot257


People also ask

What is default timeout in MongoDB?

Mongo driver uses 30s as a default value of the server selection timeout.

Why is MongoDB connection timing out?

When he tried to connect MongoDB using MongoDB client, it resulted in a server error message box that showed connection timeout error. This often happens due to settings in the MongoDB client. When the client takes too much time to connect to MongodB server than the preset timeout value, it can result in error.

Do I need to close PyMongo connection?

There's no need to close a Connection instance, it will clean up after itself when Python garbage collects it. You should use MongoClient instead of Connection ; Connection is deprecated. To take advantage of connection pooling, you could create one MongoClient that lasts for the entire life of your process.


2 Answers

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

What I was looking for is serverSelectionTimeoutMS

like image 65
sdot257 Avatar answered Sep 22 '22 20:09

sdot257


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)

like image 43
Ben Slade Avatar answered Sep 22 '22 20:09

Ben Slade