2017-08-20 6 views
1

であれば、私は私のデータベース上で開いているカーソルを持っていると私は、データベースに名前clientのコレクションを持って認識していません。私はPyMongoは、コレクションの名前は、クライアント

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. 

はここに間違って何ですか?

答えて

0

Databaseインスタンスには、次の対話型Pythonセッションで示すように、データベースのクライアントインスタンスを返すclient属性があるため、この理由があります。

>>> 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') 
関連する問題