TypeError: ‘Collection‘ object is not callable. If you meant to call the ‘insert‘ method on a ‘Colle

在学习mongoDB时,遇到了以下报错,查阅资料后解决了,希望对正在学习的小伙伴如遇到此类问题能有所帮助。
TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists.

下面看问题:

代码如下(示例):

from pymongo import MongoClient

def get_db():
    client= MongoClient(host="localhost", port=27017)#默认端口号:27017
    db = client["sylar"]
    return db

def add_one(data):
    # 拿到db
    db = get_db()
    result = db['user'].insert({"name": "小红", "age": 18})
    return result

if __name__ == '__main__':
    add_one(1)

运行后出现下面的错误:

TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists.
我们只需要将上面的" result = db['user'].insert({"name": "小红", "age": 18})" 代码中的".insert"改为".insert_one"即可,如下:

result = db['user'].insert_one({"name": "小红", "age": 18})

再次运行将不报错。

 在windows Powershell 窗口进行查询,如下图数据已存在。

到这里问题就解决啦。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值