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