0

I've inserted the following document in MongoDB:

@cherrypyexpose
def create(self):
    client = MongoClient()
    db = client.database_name        
    result = db.users.insert_one({
        "email": "email@email.com",
        "company": {
            "name": "ABC Company"
        }
     })

I would now like to retrieve the company.name which is "ABC Company".

@cherrypy.expose
def result(self):
    client = MongoClient()
    db = client.database_name        
    cursor = db.users.find({"email":"email@email.com"})
    for document in cursor:
        value = document["company.name"]
    return value

I have tried to retrieve this value using the following syntax "company.name" as I would do on relational databases but I'm getting this error: "KeyError: 'company.name'"

What would be the correct syntax to retrieve "company.name" on Mongo?

Rimo
  • 555
  • 1
  • 8
  • 18
  • `db = client.database_name` and `db.users.insert_one` is bad idea cos if db is exists, if collection exists, if key under duplicate etc. Another point is `cursor[db][collection][some_variable][entry][some values]` equal to `cursor.db.collection.some_variables.find_one({'_id':'entry'})` so mongo db don't allowed multiple collection names(this not a valid `tree` method). Cursor[db_name][collection_name] `insert,delete,update` – dsgdfg Dec 31 '16 at 15:33
  • 1
    @dsgdfg [`cursor[db][collection]` is not equal to `cursor.db.collection`](http://stackoverflow.com/questions/41262707/in-mongoshell-not-able-to-connect-to-my-collection-db-collection-name-return-n) – styvane Dec 31 '16 at 15:41
  • True, `cursor.db` is static, not usefull for large tree. Otherwise need define a lot keys and values for searching/writing an item. Need close and reopen cursor if change source db. – dsgdfg Jan 01 '17 at 09:54
  • Why the negative love? I have edited this. Can you guys please revise it or give me advise on how to improve it. – Rimo Jan 19 '18 at 19:09

1 Answers1

1

That mongo document is returned as a standard nested python dictionary. So:

value = document["company.name"]

Should be

value = document["company"]["name"]
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86