【问题标题】:Method createIndex() not callable on a collection方法 createIndex() 不可在集合上调用
【发布时间】:2019-04-10 01:43:46
【问题描述】:

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.x mongodb collections


    【解决方案1】:

    这是因为在 Pymongo 中,该方法被称为 create_index(),而不是 createIndex(),因为它在 mongo shell 中被命名。

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

    所以正确的行应该是:

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

    更多详情请参见Pymongo Collection 页面。

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2017-05-23
      • 1970-01-01
      • 2017-10-29
      • 2011-07-15
      • 1970-01-01
      • 2012-09-23
      • 2012-06-06
      相关资源
      最近更新 更多