views:

173

answers:

1

with mongodb, 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?

A: 

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.

fviktor
thats more or less what i've arrived at.its perhaps not the most efficient, but a count can be tallied using a nested field in a `reduce` function using `doc.field_name.forEach`:the `reduce` function would look something like this: function(doc, out) { doc.field.forEach(function(item_in_list) { // do something interesting with 'item_in_list' } }
Carson