2009-11-27 36 views
0

嵌套对象键是否有可能组结果在对象列表中的一个阵列中的关键?分组在MongoDB中

例如,可以说我有的调查答复(survey_responses)的表,并且每个条目代表一个单个响应。一个或多个在调查中的问题是一个多选题,因此存储的答案可能类似于:

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 
    ]}) 

我怎么能由favorite_songs_in_2009title组取分的总数量为每首歌曲的阵列中?

回答

0

看来,你唯一的选择就是做你自己的Python代码:

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'] 

你会得到在song_points变量的结果。

+0

这就是或多或少是我在到了。 它也许不是最有效的,但一个计数可以使用使用'doc.field_name.forEach'在'reduce'函数嵌套现场相吻合: 的'reduce'功能会是这个样子: 功能(DOC,出来){ doc.field.forEach(函数(item_in_list){// 做一些有趣的事情与 'item_in_list' }} – Carson 2009-11-29 04:12:34