我收集了如下文件:

{
    "_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"}
    }
}

除了每个Cathegory的最大奇数,我还需要相应的字段“source”
这提供了最大奇数。有没有办法把这个问给蒙哥?

最佳答案

在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']) ;
}

08-28 03:59