8
votes

I'm creating a collection and want to insert it in my database

I have imported pymongo and also I defined db = myClient["mydb"] this way but it says command insert requires authentication

 >>> import pymongo
 >>> from pymongo import MongoClient
 >>> myClient = MongoClient()
 >>> db = myClient.mydb
 >>> users = db.users
 >>> user1 = {"username": "nick", "password": "mysecurepass", "fav_num": 445}
 >>> user_id = users.insert_one(user1).inserted_id

line 155, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: command insert requires authentication

1

1 Answers

7
votes

It looks like the MongoDB instance you are using is set up with authentication, but when you create the connection using myClient = MongoClient() you are not giving it credentials. When you connect to the database try something like this:

client = MongoClient('example.com',
                  username='user',
                 password='password')

this will pass the correct username and password to the Mongo instance and allow you to connect. use this link for some examples on how to use authentication with pymongo.