'connection times out when trying to connect to mongodb atlas with python
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
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brandon Fuerst |
Solution 2 | tm_lv |