1

I am using pymongo to connect to my mongodb database. I am trying to call the database name and collection name in the connection string but I can't figure it out.

If I have a database name (mydb) and a collection named (mycol) this example works:

con = Connection('mymongodbhost')
d = con.mydb.mycol.find_one()
print (d)

That works fine but lets say I am defining mydb and mycol as variables, how do I call them in the connection string. So lets say I have:

db = parser.get('some_conf_file', 'db_name')
col = parser.get('some_conf_file', 'col_name')

How do I specify the db and col variables (which work that is just a code snippit) in my connection string? I've tried all sorts of combinations, and this certainly doesn't work:

d = con.db.col.find_one()
print (d)

This basically is calling the db (db) and the collection (col). But I want the variable values replaced by db and col in the example above.

Thanks.

2 Answers 2

7

Try this:

d = con[db][col].find_one()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I think I knew that once upon a time :)
0

You could use:

d = getattr(getattr(con, db), col).find_one()

Though it looks a bit inelegant.

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.