2017-01-09 3 views
0

에 $ 그룹 애그리 게이터 (aggregator)와 추가 필드를 투사 나는 다음과 같은 쿼리가 :는 pymongo

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

필드를 그룹화하려면 모든 필드를 그룹화해야합니다.

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의 부하 모두 "당마다의 사본을 줄 것이다 당신은 타임 스탬프의 배열을 얻을 $ 푸시 또는 $ addToSet을 사용할 수 있습니다 "항목 때문에 $ unwind 작품.

+0

감사합니다.하지만 실제로하고 싶은 것은'$ max'가 발견 된 별개의 시간을 잡는 것입니다. 여기서 가능합니까, 아니면 전적으로 쿼리를 다시 구성해야합니까? – MrDuk