在MongoDB中按另一个字段分组时如何汇总时间序列数据?

时间:2019-02-16 18:07:40

标签: mongodb pymongo

我有如下文件:

{u'memory_virtual': {u'percent': 55.6}, u'name': u'Device #1', u'datetime': datetime.datetime(2019, 2, 16, 17, 52, 18)}
{u'memory_virtual': {u'percent': 55.6}, u'name': u'Device #2', u'datetime': datetime.datetime(2019, 2, 16, 17, 52, 16)}
{u'memory_virtual': {u'percent': 55.7}, u'name': u'Device #1', u'datetime': datetime.datetime(2019, 2, 16, 17, 46, 56)}
{u'memory_virtual': {u'percent': 55.7}, u'name': u'Device #2', u'datetime': datetime.datetime(2019, 2, 16, 17, 46, 54)}
{u'memory_virtual': {u'percent': 55.7}, u'name': u'Device #1', u'datetime': datetime.datetime(2019, 2, 16, 17, 41, 34)}
{u'memory_virtual': {u'percent': 55.7}, u'name': u'Device #2', u'datetime': datetime.datetime(2019, 2, 16, 17, 41, 32)}

我一直在使用以下小组阶段将数据汇总为1​​5分钟间隔:

{
    '$group': {
        "_id": {
            "$toDate": {
                "$subtract": [
                    {"$toLong": "$datetime"},
                    {"$mod": [{"$toLong": "$datetime"}, 1000 * 60 * 15]}
                ]
            }
        },
        'mean': {'$avg': '$memory_virtual.percent'}
    },
}

输出如下:

{u'_id': datetime.datetime(2019, 2, 16, 18, 0), u'mean': 26.10909090909091}
{u'_id': datetime.datetime(2019, 2, 16, 17, 45), u'mean': 28.98695652173913}

我的问题是,如何将其也按“名称”字段分组?这样我将得到如下输出:

{u'_id': datetime.datetime(2019, 2, 16, 18, 0), u'name': 'Device #1', u'mean': 26}
{u'_id': datetime.datetime(2019, 2, 16, 18, 0), u'name': 'Device #2', u'mean': 27}
{u'_id': datetime.datetime(2019, 2, 16, 17, 45), u'name': 'Device #1', u'mean': 27}
{u'_id': datetime.datetime(2019, 2, 16, 17, 45), u'name': 'Device #2', u'mean': 28}

我不确定这是否重要,但作为参考,我正在使用pymongo。

1 个答案:

答案 0 :(得分:1)

您还需要在name阶段的_id中加入$group

{
    "$group": {
        "_id": {
            date: {
                "$toDate": {
                    "$subtract": [
                        {"$toLong": "$datetime"},
                        {"$mod": [{"$toLong": "$datetime"}, 1000 * 60 * 15]}
                    ]
                }
            },
            name: "$name"
        },
        "mean": {"$avg": "$memory_virtual.percent"}
    }
}