MongoDBでのネストされたオブジェクトキーによるグループ化

StackOverflow https://stackoverflow.com/questions/1806705

  •  05-07-2019
  •  | 
  •  

質問

リスト内のオブジェクトの配列で見つかったキーで結果をグループ化することは可能ですか?

たとえば、調査回答の表( survey_responses )があり、各エントリが単一の回答を表しているとします。調査の1つ以上の質問は複数選択であるため、保存されている回答は次のようになります。

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_2009 title でグループ化して、配列内の各曲の合計ポイント数を取得するにはどうすればよいですか

役に立ちましたか?

解決

あなたの唯一のオプションは、あなた自身の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 変数に結果が表示されます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top