2014-06-06 35 views
2

我希望彙總查找一個字段的最大值,同時包括文檔中的其他字段(無論選擇哪個$ max值)。

我可能要對這個錯誤的,但這裏有一個例子:

樣本數據:

{ 
    utime: 1, 
    device: "host1", 
    latest_events: ['that'] 
},{ 
    utime: 2, 
    device: "host1", 
    latest_events: ['this', 'that'] 
},{ 
    utime: 3, 
    device: "host1", 
    latest_events: ['that', 'something'] 
},{ 
    utime: 1, 
    device: "host2", 
    latest_events: ['this', 'that'] 
},{ 
    utime: 2, 
    device: "host2", 
    latest_events: ['that'] 
},{ 
    utime: 3, 
    device: "host2", 
    latest_events: ['this', 'the_other'] 
} 

這是我想要的結果:

[ 
    { 
    _id: 'host1', 
    utime: 3, 
    latest_events: ['that', 'something'] 
    },{ 
    _id: 'host2', 
    utime: 3, 
    latest_events: ['this', 'the_other'] 
    } 
] 

因此,這是我最近的猜測:

db.data.aggregate([ 
    { 
    $group: { 
     _id: '$device', 
    utime: {'$max': '$utime'}, 
    latest_events: {/* I want to select the latest_events based on the max utime*/} 
    } 
    } 
]); 

這可以概括爲「我想爲每個設備最新latest_events」。

我一直在努力解決如何做到這一點與多個聚合階段或使用項目或東西,但到目前爲止,我唯一的工作解決方案是使用多個查詢。

回答

0

你是什麼你基本上是說相當接近,但你似乎已經錯過了$last操作這將是這樣使用的文檔:在爲了

db.data.aggregate([ 
    // Sort in host and utime order 
    { "$sort": { "host": 1, "utime": 1 } }, 

    // Group on the "last" item on the boundary 
    { "$group": { 
     "_id": "$device", 
     "utime": { "$last": "$utime" }, 
     "latest_events": { "$last": "$latest_events" } 
    }} 
]) 

你基本上$sort您需要,然後在$group的字段上使用$last,您將返回成爲您按排序順序在分組邊界上發生的「最後」項目。

主要生產:

{ "_id" : "host2", "utime" : 3, "latest_events" : [ "this", "the_other" ] } 
{ "_id" : "host1", "utime" : 3, "latest_events" : [ "that", "something" ] } 

您可以在最後,如果你想以「主機」的價值觀選擇添加額外的$sort