Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Mongo中跨阵列的记录聚合_Mongodb - Fatal编程技术网

Mongodb Mongo中跨阵列的记录聚合

Mongodb Mongo中跨阵列的记录聚合,mongodb,Mongodb,我在mongo数据库中的每个文档/记录中都存储了一个数组,我需要计算该数组中每个元素的分数,并通过数组元素中的另一个字段聚合分数 我很难用英语解释我想做什么,所以这里有一个python示例,说明我想做什么 records = [ {"state": "a", "initvalue": 1, "data": [{"time": 1, "value": 2}, {"time": 2, "value": 4}]}, {"state": "a", "initvalue": 5, "dat

我在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并重新创建聚合


谢谢你的帮助

好的。我明白了。一旦我真正理解了管道的工作原理和条件函数,所有的一切都结合在一起了

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}

如果您在理解上述命令时遇到困难,这可能会有所帮助。聚合函数是命令的数组(“管道”)。尝试从数组末尾删除命令,并查看中间结果如何更改。