最近有小伙伴问题,python连接mongodb时候老是报错需要身份验证:

pymongo.errors.OperationFailure: command insert requires authentication, full error: {‘ok’: 0.0, ‘errmsg’: ‘command insert requires authentication’, ‘code’: 13, ‘codeName’: ‘Unauthorized’}

其实这个问题很简单,就是在写uri的时候把账号密码弄上去就可以了。之所以在自己电脑上没问题,是因为,你自己装的windows版本mongodb本身都是各种默认配置,又是在本机操作,基本上都不需要输入账号去验证。

如果是连接远程的比如docker中的mongodb的话,就得需要身份验证了。如下

#导入库来操作mongo
import pymongo
#获取客户端对象,这里在uri上得写上 (账号:密码@ip,如下面的 root:123456@192.168.229.10)
client=pymongo.MongoClient('mongodb://root:123456@192.168.229.10:27017/')
#拿到数据库对象
mine=client['mine']
#拿到集合对象,也就是相当于mysql的表对象
student=mine.student
#向集合中插入文档
student.insert_one({'name':'周芷若','age':18})
#查询集合所有的记录
items=student.find()
for item in items:
    print(item)

输出:

D:\softwares\work\IT\python\python.exe E:\works\python\myworkspaces\something\webcrawler\use_pymongo.py 
{'_id': ObjectId('66a85dcc1e7525907e06943c'), 'name': '张无忌', 'age': 20.0, 'gender': '男'}
{'_id': ObjectId('66a8a25861270367dea0c962'), 'name': '周芷若', 'age': 18}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部