0

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'}
4
  • Authentication failed? Probably a bad password Commented Jul 13, 2022 at 12:08
  • password, host and username are correct... Commented Jul 13, 2022 at 12:10
  • check your connection string with mongo shell or mongosh Commented Jul 13, 2022 at 12:18
  • In your URI, what is mongo? Is that a correctly configured hostname? Is it running on your local system or a remote host? Which version of Python? Which version of pymongo? Does your password use special characters? There are many possibilities. Details are required to help you. Commented Jul 13, 2022 at 22:46

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.