我在mongo数据库中的每个文档/记录中都存储了一个数组,我需要计算此数组中每个元素的分数,并将数字元素中的另一个字段聚合得分。
我很难用英语解释我想要做什么,所以这里有一个我想要做的蟒蛇示例。
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并重新发明聚合。
感谢您的帮助!
答案 0 :(得分:0)
确定。我想通了。一旦我真正理解了管道的工作方式和条件功能,一切都在一起。
from pymongo import MongoClient
client = MongoClient()
result = client.mydb.foo.aggregate([
{'$project': {'_id': 0, 'data': 1, 'initvalue': 1, 'state': 1}},
{'$unwind': '$data'},
{'$project': {
'time': '$data.time',
'score': {'$multiply': [
{'$cond': [{'$eq': ['$state', 'a']}, 1, -1]},
{'$subtract': ['$data.value', '$initvalue']}
]}
}},
{'$group': {
'_id': '$time',
'score': {'$sum': '$score'}
}},
{'$project': {'_id': 0, 'time': '$_id', 'score': 1}}
])
for record in result['result']:
print record
这产生了期望的结果
{u'score': 13, u'time': 2}
{u'score': 7, u'time': 1}