Lakal Malimage Lakal Malimage - 1 year ago 93
Python Question

How to pass MongoDB collection name as a parameter to a DB connection function-Python

I need to write a DB connection function as ,

def func(col_name):
conn = pymongo.MongoClient("localhost" , 27017)
db = conn.dbname.col_name
return db

collection name should be passed as a parameter to the function. Above function is not working. it is working if I hard-coded the collection name in the code.
Please help.

Answer Source

You can use getattr to get attribute of an object by attribute name:

getattr(conn.dbname, col_name)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download