Grouping by Nested Object Keys in MongoDB
Question
Is it possible to group results by a key found in an array of objects in a list?
For example, lets say I have a table of survey responses (survey_responses
), and each entry represents a single response. One or more of the questions in the survey is a multiple choice, so the answers stored could resemble:
survey_responses.insert({
'name': "Joe Surveylover",
'ip': "127.0.0.1",
'favorite_songs_of_2009': [
{'rank': 1, 'points': 5, 'title': "Atlas Sound: Quick Canals"},
{'rank': 2, 'points': 4, 'title': "Here We Go Magic: Fangela"},
{'rank': 3, 'points': 3, 'title': "Girls: Hellhole Ratrace"},
{'rank': 4, 'points': 2, 'title': "Fever Ray: If I Had A Heart"},
{'rank': 5, 'points': 1, 'title': "Bear in Heaven: Lovesick Teenagers"}],
'favorite_albums_of_2009': [
# and so on
]})
how can I group by the title
of favorite_songs_in_2009
to get the total number of points for each song in the array?
Solution
It seems that your only option is to do this in your own Python code:
song_points = {}
for response in survey_responses.find():
for song in response['favorite_songs_of_2009']:
title = song['title']
song_points[title] = song_points.get(title, 0) + song['points']
You'll get your results in the song_points
variable.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow