Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I get all files in collection PyMongo?

To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.

What does Find_one return PyMongo?

The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.


You can use:

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

reference


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.


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