Home > database >  Connect to MongoDB via python
Connect to MongoDB via python

Time:07-14

I'm trying to connect to mongodb using python and code:

myclient = pymongo.MongoClient("mongodb://root:password@mongo:27017/database_sample?authSource=admin")
db = myclient.database_sample
my_collection = db["database"]

but I'm getting

pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

CodePudding user response:

Your question is not clear. I can suggest you a few things. First be sure you are writing db name correctly. Second check if your password is valid. If not try to change the connection path in MongoClient since this function is client only.

CodePudding user response:

Your code is correct; Authentication failed means that at least one of your username, password or authSource is incorrect for the current database. If you have special characters in your password, that could be an issue.

At the command prompt on the same machine you are running the python code, run:

mongo 'mongodb://root:password@mongo:27017/database_sample?authSource=admin'

In most circumstances this will exhibit the same behaviour as connecting via python / pymongo.

Permissions are set at a database level, so it could be your username/password works in certain databases but not others. so at the command prompt again it's also worth trying:

mongo 'mongodb://root:password@mongo:27017/admin?authSource=admin'

and seeing if that connects or exhibits some different behaviour.

  • Related