Method createIndex() not callable on a collection

Viewed 3805

In the doc of the createIndex they say db.collection.createIndex(keys, options) so i call createIndex() with the code below. The name of my database is articles and the name of the collection is bce. Inside bce there is already a document with the field article.

class Stockage():
    def __init__(self):
        self.connexion()

    def connexion(self):
        client = pymongo.MongoClient("localhost", 27017)
        self.bce = client.articles.bce

sql = Stockage()
sql.bce.createIndex({article : "text"})

And i have the following error :

Traceback (most recent call last):

  File "<ipython-input-1132-fc8762d315d1>", line 1, in <module>
    sql.bce.createIndex({article : "text"})

  File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\collection.py", line 3321, in __call__
    self.__name.split(".")[-1])

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

Is not bce a collection ?

1 Answers

This is because in Pymongo the method is called create_index() instead of createIndex() as it is named in the mongo shell.

It also has a different format for the parameter compared to its mongo shell counterpart. Instead of accepting a document/dict as index specification, it accepts a list of tuples instead. This is because you cannot guarantee the ordering of dict keys in Python.

So the correct line should be:

sql.bce.create_index([("article", pymongo.TEXT)])

More details are available in the Pymongo Collection page.

Related