If you have come to this page, then it is because you got the following error.
pymongo.errors.ServerSelectionTimeoutError: localhost:27018: [WinError 10061] No connection could be made because the target machine actively refused it
This error is thrown when you attempt to do an operation on MongoDB, but no MongoDB server is available.
If there is no suitable server for an operation PyMongo waits for a specific amount of time defined by the constant
serverSelectionTimeoutMS. The default waiting period is 30 seconds. During this waiting period, it re-checks if the server would come online. If our python code does not find a MongoDB server, then pymongo.errors.ServerSelectionTimeoutError is thrown.
Scenarios in which pymongo.errors.ServerSelectionTimeoutError could be thrown
Following are some of the scenarios in which this Error could occur.
- PyMongo cannot connect to any server.
- If you attempt an insert into a replica set that has no primary node. And the mongo cluster did not elect a primary within the timeout window.
- If you attempt to query with a Read Preference which the replica set cannot satisfy.
How to solve pymongo.errors.ServerSelectionTimeoutError?
We have seen what could cause this error. Cross check the following things to make a connection to the MongoDB instance.
Make sure that your MongoDB instance is running. Go to processes and check if mongod.exe is running.
- Windows: Check in Task Manager
- Ubuntu: Run the command “ps -aef” and look for mongod process
Check if the URL that you provided is correct. Check for the correctness of IP address and PORT at which Mongo Daemon is running.