Python 连接mongoDB出错 pymongo.errors.OperationFailure: Authentication failed.

python连接mongoDB 时,出现 pymongo.errors.OperationFailure: Authentication failed.的错误,是因为没有赋予认证权限。
最开始的连接脚本是:


import pymongo
myclient = pymongo.MongoClient("mongodb//root:[email protected] :10000/")  xx.xx.xx.xx 是数据库服务器  root是数据库的用户名,123456是数据库的密码
mydb = myclient["test-db"]       #test-db是数据库名称 
mycol = mydb["cust_refund"]    #cust_refund是数据库的中一个数据表
for x in mycol.find({"Id":"80","testId":"1375"}):
  print(x)  

咋一看,仿佛没错,但是使用上述的语句,在运行时,报错:
pymongo.errors.OperationFailure: Authentication failed.

查看原因是因为认证权限没被赋予。

这时候,加上authenticate()函数,赋予认证权限,如下所示:

import pymongo
myclient = pymongo.MongoClient("mongodb://xx.xx.xx.xx :10000/")  xx.xx.xx.xx  是数据库服务器
mydb = myclient["test-db"]       #test-db是数据库名称 
mydb.authenticate('root','123456')
mycol = mydb["cust_refund"]    #cust_refund是数据库的中一个数据表
for x in mycol.find({"Id":"80","testId":"1375"}):
  print(x)  

这样,再次执行,就可以打开数据库了。

更多测试交流,可以加好友

Python 连接mongoDB出错 pymongo.errors.OperationFailure: Authentication failed._第1张图片

你可能感兴趣的:(Mongodb)