简体   繁体   中英

PyMongo Look up Dictionary Value when Value is in Sub-dictionary

I'm a total newbie to both Python and MongoDB, so please excuse what might be a silly question.

I Have the record below in MongoDB. Lars Torsk being the first name and last name of the record. Gunnar Torsk being the first name and last name of Lars' father.

{
    '_id': ObjectId('54840b59b6a1b322b042bde0'), 
    'First Name': 'Lars', 
    'Father': {'Last Name': 'Torsk', >'First Name': 'Gunnar', '_id': ObjectId('54840b59b6a1b322b042bddf')}, 
    'Aliases': ['rass'], 
    'Last Name': >'Torsk'
}

If I wanted to find all records of people with the first name Lars I would use:

for person in people.find({'First Name': 'Lars'}):
    print(person)

But if I want to find all records of people whom have father's whose name is Gunnar, what would I write?

I tried:

for person in people.find({'Father': {'First Name': 'Gunnar'}}):
    print(person)

But it returns no results.

Use the dot notation :

for person in people.find({'Father.First Name': 'Gunnar'}):
    print(person)

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM