如何使用pymongo编写连接到mongodb的函数

时间:2015-04-28 09:38:10

标签: python mongodb pymongo

我试图编写一个函数来连接到mongodb并返回一个集合对象。我有以下内容:

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

当我跑步时:

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

我明白了:

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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

使用client.dbname时,会调用 dbname 属性,这意味着您正在检索名为 dbname 的数据库。

同样适用于data_base.collection

解决方案:

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

替代方案:您可以使用字典样式访问:

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