connection times out when trying to connect to mongodb atlas with python

Question:

I’m trying to connect to my mongodb atlas cluster but i keep getting timed out as soon as i try to do something with my db.

The db i use was created in mongoshell and also the collection i checked their existence in mongodb compass

ERROR

pymongo.errors.ServerSelectionTimeoutError: projekt-shard-00-01-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-00-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-02-rk7ft.mongodb.net:27017: timed out

CODE

client = MongoClient("""mongodb://user:[email protected]:27017,projekt-shard-00-01-rk7ft.mongodb.net:27017,projekt-shard-00-02-rk7ft.mongodb.net:27017/projekt?ssl=true&replicaSet=projekt-shard-0&authSource=admin""")

    client.projekt.category.insert_one({type : "pants"}).inserted_id
Asked By: Alex

||

Answers:

I was having this issue for hours. It’s odd that it seems to be a connection issue, but it’s not throwing a bad auth or anything, just this timeout. The client object seems to be actually created (I could print its properties). I kept playing around and this somehow worked:

  • In the MongoDB GUI, navigate to Database Access
  • Add a test user with the same read/write permissions to everything as the initial user created upon setup
  • Change the connection string in Python to the new user’s username + password
  • Run the code

For me it finally connected and inserted successfully. After this, the original user’s connection string now worked, so I deleted the test user.

I can’t identify the root cause of this issue, but it seems like the Database Users table just needed some kind of action performed on it to refresh and begin accepting user connections.

Answered By: Brandon Fuerst

Anybody looking for a solution, if you are trying to access Atlas instance from out in the wild, check the "Network Access" tab, as i think you have to whitelist either all, or specific IP addresses

Answered By: tm_lv

SO the problem is with your IP Address,

  1. GO to the Network Access panel in MongoDB Atlas
  2. In the IP Access List section, you will find all your IP addresses
  3. Click on edit tab for the current IP address you are using
  4. There change the setting to ALLOW ACCESS FROM ANYWHERE

That’s it, it will work!

Answered By: Jappreet