从$ max对应的文档中检索其他字段

时间:2015-10-14 16:16:22

标签: mongodb aggregation-framework

我有这样的文件集合:

{
    "_id": numeric-id, 
    "timestamp": a-timestamp, 
    "odd1": "3.45", 
    "odd2": "1.95", 
    "odd3": "4.05", 
    "source": "a"
}

我设法使用此代码段聚合记录:

{
    $group: {
        _id: {tm: "$timestamp"},
        odd1: {$max: "$odd1"},
        odd2: {$max: "$odd2"},
        odd3: {$max: "$odd3"}
    }
}

除了每个导管的最大奇数,我还需要相应的字段'源'  这提供了最大的奇数。有没有办法让这个mongo?

1 个答案:

答案 0 :(得分:1)

您无法在MongoDB中执行此操作,但您可以执行第二次查询,以便在所有时间戳中找出每个maxx odd的来源:

var agg = db.collection.aggregate(
    {
        $group: {
            _id: {tm: "$timestamp"},
            odd1: {$max: "$odd1"},
            odd2: {$max: "$odd2"},
            odd3: {$max: "$odd3"}
        }
    }
);


while (agg.hasNext()) {
    var o = agg.next();
    var timestamp_odd1 = db.collection.findOne({timestamp: o['_id']['tm'],odd1:o['odd1']});
    var timestamp_odd2 = db.collection.findOne({timestamp: o['_id']['tm'],odd2:o['odd2']});
    var timestamp_odd3 = db.collection.findOne({timestamp: o['_id']['tm'],odd3:o['odd3']});
    print ("timestamp: ", o._id.tm,'  max_odd1:', timestamp_odd1['odd1'], '  ', 'source: ', timestamp_odd1['source']) ;
    print ("timestamp: ", o._id.tm,'  max_odd2:', timestamp_odd2['odd2'], '  ', 'source: ', timestamp_odd2['source']) ;
    print ("timestamp: ", o._id.tm,'  max_odd3:', timestamp_odd3['odd3'], '  ', 'source: ', timestamp_odd3['source']) ;
}