def recreate_database(): Song.collection().drop() Rating.collection().drop() Song.insert_many(songs_from_json()) Song.collection().create_index([ ('artist', TEXT), ('title', TEXT), ])
def songs_avg_rating(song_id): try: song_id = bson.ObjectId(song_id) except InvalidId: raise NotFound # TODO: should return this also when valid ObjectId, but song with the id doesn't exist try: result = next(Rating.collection().aggregate(pipeline=[ { '$match': { 'song_id': bson.ObjectId(song_id) }, }, { '$group': { '_id': '$song_id', 'average_rating': { '$avg': '$rating' }, 'min_rating': { '$min': '$rating' }, 'max_rating': { '$max': '$rating' }, }, }, ])) del result['_id'] except StopIteration: result = dict( average_rating=None, min_rating=None, max_rating=None, ) return jsonify(result)