I've inserted the following document on my mongo database using Python:
@cherrypy.expose
def create(self):
client = MongoClient()
db = client.database_name
result = db.users.insert_one({
"email": "[email protected]",
"company": {
"name": "ABC Company"
}
})
Now, I've stored the results from the collection query, using variables (company_name):
@cherrypy.expose
def result(self):
client = MongoClient()
db = client.database_name
cursor = db.users.find({"email":"[email protected]"})
for document in cursor:
email = document["email"]
company_name = document["company"]["name"]
return company_name
I would like to return the nested element as object, like: company.name instead as variable (company_name)
How can I modify my result function to store the collection results as object attributes?
1 - I using CherryPy as HTTP server. I'm not using any ORM, nor Template engine.
Use
namedtuple
fromcollections
module:and then inside the loop:
namedtuple
will you access your arguments (but read only since it's a tuple) both as positional (by index [0], [1], etc.) and as attributes (result.email). All attributes are also read-only properties, so they come with pre-bakedfget
function which can be used inmap
andfilter
.