在学习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 窗口进行查询,如下图数据已存在。

到这里问题就解决啦。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐