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

Question:

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

col = 'my_collection'
db.col.update()
Asked By: ehsan shirzadi

||

Answers:

You can use:

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

reference

Answered By: Ashoka Lella

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.

Answered By: user559633

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

Answered By: Ninad Kulkarni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.