mongodb – pymongo auth failed in python script

mongodb – pymongo auth failed in python script

Please try something like this:

client = MongoClient(mongodb://user_name:[email protected]_IP/prod-db)
db = client[prod-db]

If youve tried the above answers (from and youre still getting an error:

pymongo.errors.OperationFailure: Authentication failed.

Theres a good chance you need to add ?authSource=admin to the end of your uri.

Heres a working solution that Im using with MongoDB server version 4.2.6 and MongoDB shell version v3.6.9.

from pymongo import MongoClient

# Replace these with your server details
MONGO_PORT = 27017
MONGO_DB = database
MONGO_USER = admin

uri = mongodb://{}:{}@{}:{}/{}?authSource=admin.format(MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB)
client = MongoClient(uri)

And if youre using command line, youll get the same fix by adding the argument --authenticationDatabase admin

mongodb – pymongo auth failed in python script

For pymongo,

Try below for MongoDB 4:

Add authSource : This is the name of the database that has the collection with the user credentials.


client = MongoClient(host=<<hostname>>,
db_obj = client[db_name]

Edit 1: I have tried this on Mongo 3.x version as well. Working for that too.

Leave a Reply

Your email address will not be published. Required fields are marked *