【问题标题】:'Collection' object is not callable for both insert() and insert_one() method of a pymongo Databasepymongo 数据库的 insert() 和 insert_one() 方法都不能调用“Collection”对象
【发布时间】:2018-12-31 10:57:36
【问题描述】:

pymongo 这里遇到了一个真正的障碍性错误,这使我无法继续进行项目。我已经搜索过这个案例,但其他类似的帖子和他们的答案对我不起作用。

首先,我在跑步:

mongod v3.6.5-2-g9b2264cf14    
MongoDB shell version v3.6.5-2-g9b2264cf14

这是我最小的工作/错误产生示例:

myname@myhost ~ $ /usr/bin/python
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> db = pymongo.MongoClient("localhost:27017")
>>> db.testcollection.insert({"foo": "bar"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/collection.py", line 2344, in __call__
    self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Database' object it is failing because no such method exists.
>>>

其他 StackOverflow 主题建议改用 insert_one()。但是,这对我来说产生了相同的结果:

myname@myhost ~ $ /usr/bin/python
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> db = pymongo.MongoClient("localhost:27017")
>>> db.testcollection.insert_one({"foo": "bar"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/collection.py", line 2344, in __call__
    self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Database' object it is failing because no such method exists.

感谢任何帮助!

【问题讨论】:

    标签: python mongodb python-2.7 pymongo


    【解决方案1】:

    您尚未选择数据库。 'db' 对象是一个 MongoClient 对象。您需要获取一个数据库对象。

    试试这个:

    db[<database-name>][<collectin-name>].insert(<document>);
    

    【讨论】:

    • 不应该是client[&lt;database-name&gt;][&lt;collection-name&gt;].insert(&lt;document&gt;);吗?
    【解决方案2】:

    试试:

    import pymongo
    client = pymongo.MongoClient()
    db = client[ "testdb" ] # makes a test database called "testdb"
    col = db[ "testcol" ] #makes a collection called "testcol" in the "testdb"
    col.insert_one( {"foo" : "bar" }) #add a document to testdb.testcol
    

    【讨论】:

    • 为了举例,我可能会更改“测试”标签之一
    • 你是对的。进行了一些更改以区分数据库和集合。
    猜你喜欢
    • 2019-04-12
    • 2012-03-10
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2021-09-27
    • 2022-01-08
    • 2020-11-25
    相关资源
    最近更新 更多