【问题标题】:PyMongo not recognizing if the name of the collection is clientPyMongo 无法识别集合的名称是否为客户端
【发布时间】:2018-01-28 22:09:18
【问题描述】:

我在我的数据库上打开了一个游标,并且我在数据库中有一个名为 client 的集合。当我尝试执行类似

的查询时
def connect_to_primary(host, port):
    """this function is to connect to primary host in a replicaset"""
    connection = MongoClient(str(host), int(port))
    admindb = connection.admin
    pri_host_port_con = admindb.command("isMaster")
    primary_con = pri_host_port_con['primary']
    pri_host_port = primary_con.replace(':', ' ').split()
    pri_host = pri_host_port[0]
    pri_port = pri_host_port[1]
    final_connection = MongoClient(str(pri_host), int(pri_port))
    return final_connection

connect_to_primary(host,port)[db].client.find({}).distinct('clientid')

我收到以下错误:

File "/usr/lib64/python2.7/site-packages/pymongo/database.py", line 1116, in __call__
    self.__name, self.__client.__class__.__name__))
TypeError: 'Database' object is not callable. If you meant to call the 'find' method on a 'MongoClient' object it is failing because no such method exists.

这里有什么问题?

【问题讨论】:

    标签: mongodb mongodb-query pymongo pymongo-3.x


    【解决方案1】:

    之所以得到这个,是因为Database 实例有一个client 属性,该属性返回数据库的客户端实例,如以下交互式 Python 会话所示。

    >>> import pymongo
    >>> connection = pymongo.MongoClient()
    >>> db = connection["test"]
    >>> db
    Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test')
    >>> db.client
    MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)
    

    唯一的解决方案是使用get_collection 方法或[] 运算符。

    >>> db["client"]
    Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test'), 'client')
    >>> db.get_collection("client")
    Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test'), 'client')
    

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2021-05-11
      • 2020-11-05
      • 1970-01-01
      相关资源
      最近更新 更多