how can i validate username password for mongodb authentication through pymongo? how can i validate username password for mongodb authentication through pymongo? mongodb mongodb

how can i validate username password for mongodb authentication through pymongo?


As an FYI, you can use the URI string format as well. The pseudocode looks like this:

pymongo.MongoClient('mongodb://user:password@server:port/')

Here's a simple connection code block with auth:

import pymongoconn = pymongo.MongoClient('mongodb://root:pass@localhost:27017/')db = conn['database']coll = db['collection']

There are more options for the query string here: http://docs.mongodb.org/manual/reference/connection-string/

Hope that helps = looks like you already have it though. Happy coding!!


Just adding more to provided solutions.

I have been using as URI connection string and credentials being provided as f string it helps to reduce number of lines. One thing to note is about special characters in password where we convert using urllib package as shown below.

import urllib.parsefrom pymongo import MongoClienthost = "localhost"port = 27017user_name = "myuser"pass_word = "Pass@123"  db_name = "mydb"  # database name to authenticate# if your password has '@' then you might need to escape hence we are using "urllib.parse.quote_plus()" client = MongoClient(f'mongodb://{user_name}:{urllib.parse.quote_plus(pass_word)}@{host}:{port}/{db_name}') 


It's worked for me.

Here you can connect mongodb to python by using authentication username and password.

import pymongoDATABASE_NAME = "your_database_name"DATABASE_HOST = "localhost"DATABASE_USERNAME = "database_username"DATABASE_PASSWORD = "database_password"try:    myclient = pymongo.MongoClient( DATABASE_HOST )    myclient.test.authenticate( DATABASE_USERNAME , DATABASE_PASSWORD )    mydb = myclient[DATABASE_NAME]    print("[+] Database connected!")except Exception as e:    print("[+] Database connection error!")    raise e

By default Mongodb uses 27017 port