使用pymongo庫里的MongoClient連接MongoDB,
創(chuàng)建連接對象只設置了IP和port
import pymongo
client = MongoClient(host='localhost',port=27017)
然后出現(xiàn)以下的錯誤
pymongo.errors.OperationFailure: not authorized on test to execute command
原因是數(shù)據(jù)庫開啟了權限認證,連接對象沒有使用認證
解決如下:
client = pymongo.MongoClient(host='localhost',port=27017,username='admin',password='12345',authSource='admin',authMechanism='SCRAM-SHA-1')
其中authSource可以省略,默認是admin,是當前用戶所在的數(shù)據(jù)庫
在MongoDB3.0及以上,默認使用SCRAM-SHA-1作為身份驗證機制
具體參考:http://api.mongodb.com/python/current/examples/authentication.html#support-for-special-characters-in-usernames-and-passwords