Is it possible to use Variable for collection name

2020-02-23 05:57发布

问题:

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])