Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

mongodb

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.

like image 321
Lakal Malimage Avatar asked Jan 24 '15 10:01

Lakal Malimage


2 Answers

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

getattr(conn.dbname, col_name)
like image 146
falsetru Avatar answered Sep 28 '22 02:09

falsetru


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

You can do the same from the client if you want to pass in the database name:

def func(db_name, col_name):
    conn = pymongo.MongoClient("localhost" , 27017)
    return conn[db_name][col_name]
like image 30
Bernie Hackett Avatar answered Sep 28 '22 01:09

Bernie Hackett