使用PyMongo时,Collection对象不可调用错误

Jas*_*pel 46 python mongodb pymongo

继PyMongo 教程之后,在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.
Run Code Online (Sandbox Code Playgroud)

网上有一些帖子讨论了这个错误,但似乎都是用户调用已弃用的名称.

我在这里做错了什么指导?

Nei*_*unn 55

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

2.8版本的教程指向.insert(),而不是方法:

posts.insert({'a':1})
Run Code Online (Sandbox Code Playgroud)

由于.insert_one()仅适用于3.0b驱动程序.

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

这似乎是当前"搜索引擎响应"的错误,将"beta版本"与"当前"相匹配.


sty*_*ane 17

问题是您正在遵循当前发行版文档中的教程,但实际安装了PyMongo 2.8.

这个insert_one()方法是PyMongo 3.0中的新方法,现在在PyMongo 2.9中向后移植.很明显,您需要安装PyMongo 2.9或更新版本才能使用新的API功能.

您可以使用pip类似安装或升级您的驱动程序.

python -m pip install -U pymongo
Run Code Online (Sandbox Code Playgroud)