我有如下文件:
{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)}
我一直在使用以下小组阶段将数据汇总为15分钟间隔:
{
'$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。
答案 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"}
}
}