2017-01-09 64 views
0

我有以下查詢:

HOST_USAGE.aggregate([{ 
    '$match': {'sysstat.host.nodename': host} 
    }, { 
     '$project': {'ts': '$sysstat.host.statistics.timestamp'} 
    }, { 
     '$unwind': '$ts' 
    }, { 
     '$unwind': '$ts.cpu-load-all.cpu' 
    }, { 
     '$group': { 
      '_id': 0, 
      'all-usr': {'$max': '$ts.cpu-load-all.cpu.usr'} 
     } 
    }]) 

然而,有,我想抓住一個附加字段,$sysstat.host.statistics.timestamp[*].time

enter image description here

我我試過了,

'$group': { 
    '_id': 0, 
    'all-usr': {'$max': '$ts.cpu-load-all.cpu.usr'}, 
    'time': '$ts.time' 
} 

但是這個gi一個錯誤:pymongo.errors.OperationFailure: exception: the group aggregate field 'time' must be defined as an expression inside an object。我怎樣才能$group某些字段,並將其他字段投影到返回的數據集?

回答

1

如果您正在對任何字段進行分組,您必須對所有字段進行分組。你可以使用$推或$ addToSet獲得時間戳的數組:

HOST_USEAGE.aggregate([{ 
    '$match': {'sysstat.host.nodename': 1} 
}, { 
    # Rename the field for brevity. 
    '$project': {'ts': '$sysstat.host.statistics.timestamp'} 
}, { 
    '$unwind': '$ts' 
}, { 
    '$unwind': '$ts.cpu-load-all.cpu' 
}, { 
    '$group': { 
     '_id': 0, 
     'all-usr': {'$sum': '$ts.cpu-load-all.cpu.usr'}, 
     'times': {'$addToSet': '$ts.time'} 
    } 
}]))) 

我建議$addToSet避免輸出數組中重複次數:$push,你會給每次的一個副本每個「CPU負載,所有「因爲$ unwind是如何工作的。

+0

謝謝,但我想要做的是實際抓住'$ max'發現的不同時間。這是可能的,還是我需要重新整理我的查詢? – MrDuk