1

I was trying to connect to Mongo collection where each time collection and query is different.I'm trying to write a function where user will pass collection name and query string and user will get cursor as a result. But this function is not connecting to collection passed in variable but instead appends variable name to connection object, here 'coll'. it is also appending the query string instead of executing it. I have tried executing query by hard coding collection name.But in that case as well it doesn't executes the query. my code goes like this:

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
styvane
  • 59,869
  • 19
  • 150
  • 156
fhulprogrammer
  • 599
  • 2
  • 7
  • 16

2 Answers2

0

In this function we can return result from various collection and 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
cehmja
  • 130
  • 6
0

You should make your connection outside your function using pymongo.MongoClient. Also here I am using the 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() 

Demo

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'}
styvane
  • 59,869
  • 19
  • 150
  • 156
  • I'm getting this error: ` result=_collection.find(query_string) File "C:\Python34\lib\site-packages\pymongo\collection.py", line 877, in find return Cursor(self, *args, **kwargs) File "C:\Python34\lib\site-packages\pymongo\cursor.py", line 97, in __init__ raise TypeError("spec must be an instance of dict") TypeError: spec must be an instance of dict` – fhulprogrammer Feb 11 '15 at 07:25
  • @fhulprogrammer I edited my answer with **DEMO**. BTW How are you calling the function? `query_string` should be an `instance` of `dict` or `keyword` argument – styvane Feb 11 '15 at 07:32
  • query_string="{$and:[{query1},{query2}]}" when I'm calling as mongo_result('collection',query_string) it is throwing error: TypeError: mongo_result() takes 1 positional argument but 2 were given. when only 1 parameter,i.e., collection name is passed it works fine. – fhulprogrammer Feb 11 '15 at 09:46
  • @fhulprogrammer see this answer for keyword argument . http://stackoverflow.com/a/1419160/3100115 – styvane Feb 11 '15 at 11:57