Pymongo.errors.operationfailure: authentication failed., full error: {‘ok’: 0.0, ‘errmsg’: ‘authentication failed.’, ‘code’: 18, ‘codename’: ‘authenticationfailed’}

Error: pymongo.errors.OperationFailure: authentication failed.

Full Error: {‘ok’: 0.0, ‘errmsg’: ‘authentication failed.’, ‘code’: 18, ‘codename’: ‘authenticationfailed’}

This error occurs when attempting to authenticate with a MongoDB server, but the authentication process fails. It indicates that the provided credentials (username and password) are incorrect or not authorized to access the specified MongoDB database.

To resolve this issue, you should verify the following:

  • Check the correctness of the username and password used for authentication.
  • Ensure that the user has the necessary privileges to access the database (e.g., read, write).
  • Confirm that the authentication mechanism is correct. MongoDB supports different authentication mechanisms, such as SCRAM-SHA-1, MONGODB-CR, etc. Ensure that you are using the appropriate mechanism for your MongoDB deployment.
  • Check the connection string or connection parameters used to connect to the MongoDB server. Make sure they include the correct authentication details.
  • If using a MongoDB replica set, ensure that all the replica set members have the same authentication configuration.

Here is an example of how to authenticate using pymongo in Python:


import pymongo

# MongoDB connection details
host = 'mongodb://localhost:27017'
username = 'myuser'
password = 'mypassword'
database = 'mydatabase'

# Connect to MongoDB and authenticate
client = pymongo.MongoClient(host)
db = client[database]
db.authenticate(username, password)

# Perform database operations
# ...

Leave a comment