2

I've created a user for my database in mongodb. I've tested with mongo shell to make sure that the user has proper privileges to access the database. Now I want to use my Python program to access the database, and I use PyMongo. If I run mongod in unauthorized mode (without option --auth), the Python client works fine. However, when I use --auth option, the Python client doesn't work any more. In fact, it reports unauthorized error, which is easy to understand because I didn't change anything in the code. Here is the code to connect my test database:

from pymongo import MongoClient
client = MongoClient()
db = client.test
cursor = db.restaurants.find()
for document in cursor:
    print(document)

My question is how can I change the Python code to use username/password created previously? I've looked at the client documentation but there is not information for it.

lenhhoxung
  • 2,530
  • 2
  • 30
  • 61

2 Answers2

4
client = MongoClient("mongodb://username:password@server/dbname")

This is the normal format for telling the client where and how to connect. The way you are using (with no parameters at all) defaults to a local mongo install, on the default port, with no authentication.

Danielle M.
  • 3,607
  • 1
  • 14
  • 31
  • Be aware that if you password contains reserved characters (like ':' or '@') you'll run into problems. As I had this issue, I created a [question about that](http://stackoverflow.com/questions/39237813/how-to-escape-in-a-password-in-pymongo-connection). – gmauch Aug 30 '16 at 22:38
2

Besides Danielle's answer you can also use authenticate method for that. Your code would look like this:

from pymongo 
import MongoClient 
client = MongoClient() 
db = client.test 
db.authenticate('user', 'password', mechanism=<either 'SCRAM-SHA-1' or 'MONGODB-CR', being 'MONGODB-CR' the default authentication mechanism Before MongoDB 3.0>)
cursor = db.restaurants.find() 
for document in cursor:
    print(document)
Community
  • 1
  • 1
gmauch
  • 1,316
  • 4
  • 25
  • 39