ehsan shirzadi
ehsan shirzadi

Reputation: 4859

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

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

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

Upvotes: 32

Views: 18024

Answers (3)

Ninad Kulkarni
Ninad Kulkarni

Reputation: 476

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

Upvotes: 1

user559633
user559633

Reputation:

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.

Upvotes: 7

Ashoka Lella
Ashoka Lella

Reputation: 6729

You can use:

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

reference

Upvotes: 67

Related Questions