Reputation: 375
I'm new to Python and I'm trying to connect to a MongoDB ReplicaSet, but when I try to connect to the database I get the following error in the "for x in mydoc" statement:
File "C:\Users\Nahuel Gabioud\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\helpers.py", line 159, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: Authentication failed.
The code It's the following
import pymongo
import urllib
password = urllib.parse.quote_plus("moica2$PerformanceGGR!!")
try:
myclient = pymongo.MongoClient("mongodb://performance:"+password+"@db-mdb-30.serverurl:27017,db-mdb-31.serverurl:27017,db-mdb-32.serverurl:27017/?authMechanism=SCRAM-SHA-256&replicaSet=rs30&readPreference=primaryPreferred")
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")
mydb = myclient["moica2"]
mycol = mydb["moicaTickets"]
myquery = {"nroTkt": "190701PD0100"}
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
input()
For security reasons, I didn't post the real url and used "serverurl" instead.
As you can see, I'm using the connection string as in https://docs.mongodb.com/manual/reference/connection-string/#standard-connection-string-format
The exception is not caught in the try and except. The error appears in "for x in mydoc".
Upvotes: 0
Views: 850
Reputation: 469
You have to mention like this way:
client = MongoClient('X.X.X.X',port=27017,username='iamlogin', password='abcd',authSource='xyz_db')
authSource of your username accessible database name
Upvotes: 1
Reputation: 4094
Authentication failed would lead you to believe that the ID / Password is incorrect. If you're behind a corporate firewall, though, it might be a connectivity issue and a poor error message.
I'd suggest downloading / installing Compass and see if that connects with the same connection string / credentials.
https://www.mongodb.com/products/compass
if it does work, I'd suggest this line
urllib.parse.quote_plus("moica2$PerformanceGGR!!")
is doing something to change the password, and that is where it is failing.
P.s. I'd edit the password out of your question!
Upvotes: 2