使用pymongo连接MongoDB

2018-06-03  本文已影响0人  认真点啊

使用pymongo库里的MongoClient连接MongoDB,
创建连接对象只设置了IP和port

import pymongo
client = MongoClient(host='localhost',port=27017)

然后出现以下的错误
pymongo.errors.OperationFailure: not authorized on test to execute command
原因是数据库开启了权限认证,连接对象没有使用认证
解决如下:

client = pymongo.MongoClient(host='localhost',port=27017,username='admin',password='12345',authSource='admin',authMechanism='SCRAM-SHA-1')

其中authSource可以省略,默认是admin,是当前用户所在的数据库
在MongoDB3.0及以上,默认使用SCRAM-SHA-1作为身份验证机制
具体参考:http://api.mongodb.com/python/current/examples/authentication.html#support-for-special-characters-in-usernames-and-passwords

上一篇下一篇

猜你喜欢

热点阅读