7

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.

2 Answers 2

6

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

getattr(conn.dbname, col_name)
Sign up to request clarification or add additional context in comments.

Comments

4
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.