方法 createIndex() 不可在集合上调用

TmS*_*mth 6 collections mongodb python-3.x

createIndex他们说的文档中,db.collection.createIndex(keys, options)createIndex()用下面的代码调用。我的数据库articles的名称是,集合的名称是bce. 里面bce已经有一个带有字段的文档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"})
Run Code Online (Sandbox Code Playgroud)

我有以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

是不是bce收藏?

kev*_*adi 12

这是因为在 Pymongo 中,该方法被调用create_index()而不是createIndex()mongoshell 中命名。

与其mongo对应的shell相比,它还具有不同的参数格式。它不接受文档/字典作为索引规范,而是接受元组列表。这是因为您无法保证 Python 中 dict 键的顺序。

所以正确的行应该是:

sql.bce.create_index([("article", pymongo.TEXT)])
Run Code Online (Sandbox Code Playgroud)

Pymongo Collection页面提供了更多详细信息。