当查询和集合名称不同时,通过 python 执行 mongo 查询时出错

Error in mongo query execution through python when queries and collection name are varying

我试图连接到 Mongo 集合,其中每次收集和查询都是 different.I我正在尝试编写一个函数,用户将在其中传递集合名称和查询字符串,用户将获得游标因此。但是这个函数并没有连接到传入变量的集合,而是将变量名附加到连接对象,这里是'coll'。它还附加查询字符串而不是执行它。我曾尝试通过硬编码集合 name.But 执行查询,在这种情况下它也不执行查询。我的代码是这样的:

def mongo_result(coll,query_string):
     conn_obj=mongo_connection() #mongo_connection()-returns connection    object
    _collection=conn_obj.coll #collection: name of collection passed #while calling function**#Query string: query passed to function**
    result=_collection.query_string #errorneous statement
    return result

在这个函数中我们可以 return 来自各种集合的结果和 query_types

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.test


def query(coll_name, query_type, *args):

    coll = db[coll_name]   # coll - your collection
    # here you have common methods of mongo
    _ = {
        'insert': coll.insert,
        'update': coll.update,
        'find': coll.find,
        'findOne': coll.find_one
}
    return _[query_type](*args)

# iterate through result
for x in query('testtable', 'find', {'a': 'a'}):
    print x

您应该使用 pymongo.MongoClient 在您的函数 外部 建立连接。 同样在这里我使用 find method in my function but you can execute any other operation

import pymongo

connection = pymongo.MongoClient()
db = connection.test



def mongo_result(coll, **query_string):
    _collection = pymongo.collection.Collection(db, coll)
    if query_string:
        return _collection.find(query_string)
    return _collection.find() 

演示

result = mongo_result('spam') #spam is my collection's name.
for doc in result:
    print(doc)

{'_id': ObjectId('54dafa385a28b3f71731efbd'), 'name': 'search string'}
{'_id': ObjectId('54dafa3d5a28b3f71731efbe'), 'name': 'search string1'}
{'_id': ObjectId('54dafa3f5a28b3f71731efbf'), 'name': 'search string2'}