Collection object is not callable 错误与 PyMongo

Collection object is not callable error with PyMongo

跟随 PyMongo tutorial 并在对集合调用 insert_one 方法时遇到错误。

In [1]: import pymongo

In [2]: from pymongo import MongoClient

In [3]: client = MongoClient()

In [4]: db = client.new_db

In [5]: db
Out[5]: Database(MongoClient('localhost', 27017), u'new_db')

In [6]: posts = db.posts

In [7]: posts.insert_one({'a':1})
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-2271c01f9a85> in <module>()
----> 1 posts.insert_one({'a':1})

C:\Anaconda\lib\site-packages\pymongo-2.8-py2.7-win32.egg\pymongo\collection.py in __call__(self, *a
rgs, **kwargs)
   1771                         "call the '%s' method on a 'Collection' object it is "
   1772                         "failing because no such method exists." %
-> 1773                         self.__name.split(".")[-1])

TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Collection' object it is failing because no such method exists.

网上有一些讨论此错误的帖子,但似乎都是在用户调用已弃用的名称时出现的。

关于我在这里做错了什么的任何指导?

问题是您正在按照当前版本文档中的教程进行操作,但实际上安装了 PyMongo 2.8。

insert_one() method is new in PyMongo 3.0 now backported in PyMongo 2.9。很明显,您需要安装 PyMongo 2.9 或更新版本才能使用新的 API 功能。

您可以使用 pip 之类的方式安装或升级您的驱动程序。

python -m pip install -U pymongo

这是一个明确的问题,但这里的问题似乎是您正在阅读 "beta" 发布文档,但很可能您实际上最多安装了 "pymongo" 2.8,而不是“ 3.0b”在您引用的 link 中提到。

2.8 release tutorial points to the .insert() 方法改为:

posts.insert({'a':1})

因为 .insert_one() 仅在 3.0b 驱动程序中可用。

要么强制安装 "beta" 驱动程序,要么使用稳定的驱动程序和可用方法。

这似乎是当前 "search engine response" 与 "beta release" 匹配为 "current" 的错误。

我也遇到了同样的问题。当我尝试使用命令升级我的 PyMongo 发行版时,

pip install -U pymongo

我收到以下错误:

error: could not create '/usr/local/lib/python2.7/dist-packages/pymongo': Permission denied

显然,在我的发行版中,由于权限不足,安装程序无法在 dist-packages 文件夹中创建库。所以,我通过授予它写入权限并重新安装 PyMongo 驱动程序解决了这个问题:

cd /usr/local/lib/python2.7/
sudo chmod 0777 dist-packages
pip install -U pymongo

希望对您有所帮助。