문제

목록의 객체 배열에있는 키로 결과를 그룹화 할 수 있습니까?

예를 들어, 설문 조사 테이블이 있다고 가정 해 봅시다 (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
    ]})

어떻게 그룹화 할 수 있습니까? titlefavorite_songs_in_2009 배열에서 각 노래의 총점 수를 얻으려면?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top