Following along the PyMongo tutorial and am getting an error when calling the insert_one method on a collection.

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.

There are a few posts online that discuss this error but all seem to be when the user calls a deprecated name.

Any guidance on what I am doing wrong here?

Solution 1

It is a clear question but the problem here seems to be that you are reading from the "beta" release documentation but in all likelihood you actually at most have "pymongo" 2.8 installed rather than the "3.0b" referred to in the link you quote.

The 2.8 release tutorial points to the .insert() method instead:

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

Since .insert_one() is only available in the 3.0b driver.

Either force the installation of the "beta" driver or live with a stable driver and the available methods.

This seems to be the fault of the current "search engine response" matching the "beta release" as "current".

Solution 2

The problem is that you are following the tutorial from the current release documentation but actually have PyMongo 2.8 installed.

The insert_one() method is new in PyMongo 3.0 now backported in PyMongo 2.9. So clearly you will need to install PyMongo 2.9 or newer version in order to use the new API feature.

You can install or upgrade your driver using pip like.

python -m pip install -U pymongo

Solution 3

I was facing the same problem too. When I tried upgrading my PyMongo distribution using the command,

pip install -U pymongo

I got the following error :

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

Apparently, on my distro, the installer was not able to create a library in the dist-packages folder due to insufficient permission privileges. So, I solved the problem by granting it write permissions and re-installing the PyMongo driver:

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

Hope this helps.