Gagan
Gagan

Reputation: 1923

Pymongo not able to connect to the database: pymongo.errors.ServerSelectionTimeoutError: connection closed

I want to read the collection through pymongo but I am getting the following error:

Traceback (most recent call last): File "C:/Users/GSingh/PycharmProjects/MC/quizQuestionAnswers.py", line 21, in pprint.pprint(posts.find_one()) File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\collection.py", line 1262, in find_one for result in cursor.limit(-1): File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\cursor.py", line 1189, in next if len(self.__data) or self._refresh(): File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\cursor.py", line 1087, in _refresh self.__session = self.__collection.database.client._ensure_session() File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\mongo_client.py", line 1558, in _ensure_session return self.__start_session(True, causal_consistency=False) File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\mongo_client.py", line 1511, in __start_session server_session = self._get_server_session() File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\mongo_client.py", line 1544, in _get_server_session return self._topology.get_server_session() File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\topology.py", line 427, in get_server_session None) File "C:\Users\GSingh\AppData\Local\Continuum\anaconda2\lib\site-packages\pymongo\topology.py", line 199, in _select_servers_loop self._error_message(selector)) pymongo.errors.ServerSelectionTimeoutError: connection closed

Following is the code I am running:

from pymongo import MongoClient
import pprint

username = 'username'
password = 'Password'

uri = "mongodb://"+username+":"+password+"@mc-*****.mongodb.net:27017/?authMechanism=SCRAM-SHA-256"
client = MongoClient(uri)
database = client["sws-quiz"]
collection = database["attempts"]

try:
    posts = database.posts
    pprint.pprint(posts.find_one())

finally:
    client.close()

Upvotes: 1

Views: 1875

Answers (1)

Gagan
Gagan

Reputation: 1923

It was because I did not do ssl=True

Upvotes: 2

Related Questions