Returning nested collection elements as objects in Python

355 Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

Use namedtuple from collections module:

from collections import namedtuple
company = namedtuple('company ', 'name') 
document = namedtuple('document ', 'email, company')

and then inside the loop:

for row in cursor:
    result = document(row["email"], company(row["company"]["name"]))
    yield result # or 'return result' if there is only one of them

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-baked fget function which can be used in map and filter.