首页 > 解决方案 > 方法 createIndex() 不可在集合上调用

问题描述

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"})

我有以下错误:

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.

是不是bce收藏?

标签: python-3.xmongodbcollections

解决方案


这是因为在 Pymongo 中调用该方法create_index()而不是在shellcreateIndex()中命名该方法。mongo

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

所以正确的行应该是:

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

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


推荐阅读