我在 mongo 数据库的每个文档/记录中存储了一个数组,我需要计算这个数组中每个元素的分数,并通过数组元素中的另一个字段聚合分数。
我很难用英语解释我想要做什么,所以这里有一个我想要做的 python 示例。
records = [
{"state": "a", "initvalue": 1, "data": [{"time": 1, "value": 2}, {"time": 2, "value": 4}]},
{"state": "a", "initvalue": 5, "data": [{"time": 1, "value": 7}, {"time": 2, "value": 9}]},
{"state": "b", "initvalue": 4, "data": [{"time": 1, "value": 2}, {"time": 2, "value": 1}]},
{"state": "b", "initvalue": 5, "data": [{"time": 1, "value": 3}, {"time": 2, "value": 2}]}
]
def sign(record):
return 1 if record["state"] == "a" else -1
def score(record):
return [{"time": element["time"], "score": sign(record) * (element["value"] - record["initvalue"])} for element in record["data"]]
scores = []
for record in records:
scores += score(record)
sums = {}
for score in scores:
if score["time"] not in sums:
sums[score["time"]] = 0
sums[score["time"]] += score["score"]
print '{:>4} {:>5}'.format('time', 'score')
for time, value in sums.iteritems():
print '{:>4} {:>5}'.format(time, value)
a
这会为状态和状态计算稍微不同的分数函数b
,然后汇总每个时间条目的分数。
这是结果
time score
1 7
2 13
我试图弄清楚如何在 mongo 中做到这一点,而不是将记录拉入 python 并重新发明聚合。
谢谢您的帮助!