DBWeinstein
DBWeinstein

Reputation: 9499

how do I write a function for connecting to mongodb using pymongo

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?

Upvotes: 1

Views: 1171

Answers (1)

Yannick Clybouw
Yannick Clybouw

Reputation: 161

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

Upvotes: 4

Related Questions