Is it possible to use Variable for collection name using pymongo?

爱⌒轻易说出口 提交于 2019-12-18 11:45:36

问题


Is it possible to use Variable for collection name using pymongo? for example:

col = 'my_collection'
db.col.update()

回答1:


You can use:

col = 'my_collection'
db[col].update()

reference




回答2:


You're trying to call a method from a string. This is not specific to pymongo.

You can use getattr to see if the string exists as an attribute on your db object, then call it.

e.g.

my_collection = getattr(col, 'my_collection')
my_collection.update()

edit: Note that using the getattr approach allows for exception handling in the case that the string is not a method or attribute of col.




回答3:


Ashoka Lella's answer is perfect. One bit of addition to it is to have this statement in your flask model's class.

__collection__="default"  #Any default collection, which may or may not be used by the application

Just because your collection is in a variable, does not mean that you can skip the definition of the collection attribute. I am pasting my code below where I used this way.

class Collection(Document):
 __collection__ = "collection_1"
 structure = {
    "name": str,
    "email": str,
    "status": bool,
    "extra": dict
 }
 required_fields = ["name", "email"]    
 default_values = {"status": "inactive", "extra": {}}

 def insertDocument(self, data):
    print "model : " + data["collection"]
    db[data["collection"]].insert(data["data"])
    return "from model"

Don't forget to register your class name on the db variable - db.register([Collection])



来源:https://stackoverflow.com/questions/24799988/is-it-possible-to-use-variable-for-collection-name-using-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!