1

I'm trying to write a function to connect to mongodb and return a collection object. I have the following:

def getCollection(dbname,collection): client = MongoClient() data_base = client.dbname collObject = data_base.collection return collObject 

When I run:

collection = getCollection(client, "hkpr_restore", "agents") print collection 

I get:

Collection(Database(MongoClient('localhost', 27017), u'dbname'), u'collection') 

What am I doing wrong?

1

1 Answer 1

4

When using client.dbname, the attribute dbname is called, meaning you are retrieving the database named dbname.

Same applies for data_base.collection.

Solution:

def getCollection(dbname, collection): client = MongoClient() data_base = getattr(client, dbname) collObject = getattr(data_base, collection) return collObject 

Alternative: you can use dictionary style access:

def getCollection(dbname, collection): client = MongoClient() data_base = client[dbname] collObject = data_base[collection] return collObject 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.