Connect mongodb from Python in authorized mode
<p>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 <a href="http://api.mongodb.com/python/current/tutorial.html" rel="nofollow">PyMongo</a>. If I run mongod in unauthorized mode (without option <code>--auth</code>), the Python client works fine. However, when I use <code>--auth</code> option, the Python client doesn't work any more. In fact, it reports <code>unauthorized error</code>, which is easy to understand because I didn't change anything in the code. Here is the code to connect my <code>test</code> database:</p>

<pre><code>from pymongo import MongoClient
client = MongoClient()
db = client.test
cursor = db.restaurants.find()
for document in cursor:
    print(document)
</code></pre>

<p>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.</p>

<p>Besides <a href="http://stackoverflow.com/a/39150113/4385621">Danielle's answer</a> you can also use <a href="http://api.mongodb.com/python/current/examples/authentication.html#scram-sha-1-rfc-5802" rel="nofollow">authenticate</a> method for that. Your code would look like this:</p>

<pre><code>from pymongo 
import MongoClient 
client = MongoClient() 
db = client.test 
db.authenticate('user', 'password', mechanism=&lt;either 'SCRAM-SHA-1' or 'MONGODB-CR', being 'MONGODB-CR' the default authentication mechanism Before MongoDB 3.0&gt;)
cursor = db.restaurants.find() 
for document in cursor:
    print(document)
</code></pre>

python mongodb