PHP中如何从MongoDB获取按升序排列的最后N条记录
如何将MongoDB查询的最后60条记录按时间戳升序返回
我明白你的需求了——你需要获取MongoDB集合里最新的60条记录,但最终要按time_stamp从小到大(升序)排列,而不是现在的从新到旧的降序。
你的原代码是先按降序排序取前60条(也就是最新的60条),但结果顺序是从新到旧。要改成升序,这里有两种简单可行的方案:
方案1:PHP端反转数组(改动最小)
保持原有的查询逻辑(确保取到最新60条),只需要在生成JSON数组后,把数组反转即可。这种方法改动最少,适合快速解决问题。
修改后的完整代码:
<?php header("Content-type: text/json"); require ($_SERVER['DOCUMENT_ROOT'] . '/grafic/mongodb_php/vendor/autoload.php'); $client = new MongoDB\Client; $traficodb = $client->traficodb; $trafico_total = $traficodb->trafico_total; $filter = []; // 继续按降序取最新的60条记录 $options = ['sort' => ['time_stamp' => -1], 'limit' => 60]; $show = $trafico_total->find($filter, $options); $json = []; foreach ($show as $collection) { $json[] = [ strtotime($collection["time_stamp"]) * 1000, (int)$collection["tx"], (int)$collection["rx"] ]; } // 关键:反转数组,将降序的最新记录转为升序排列 $json = array_reverse($json); echo json_encode($json); ?>
方案2:MongoDB聚合管道处理(数据库端完成排序)
如果你希望把排序逻辑放在数据库层,避免PHP端的数组操作,可以使用聚合管道:先按降序取60条,再对这60条按升序重新排序。
修改后的完整代码:
<?php header("Content-type: text/json"); require ($_SERVER['DOCUMENT_ROOT'] . '/grafic/mongodb_php/vendor/autoload.php'); $client = new MongoDB\Client; $traficodb = $client->traficodb; $trafico_total = $traficodb->trafico_total; // 聚合管道:先取最新60条,再反转排序 $pipeline = [ ['$sort' => ['time_stamp' => -1]], ['$limit' => 60], ['$sort' => ['time_stamp' => 1]] ]; $show = $trafico_total->aggregate($pipeline); $json = []; foreach ($show as $collection) { $json[] = [ strtotime($collection["time_stamp"]) * 1000, (int)$collection["tx"], (int)$collection["rx"] ]; } echo json_encode($json); ?>
两种方案都能实现你要的效果:比如当time_stamp为1-9时,最终会返回5、6、7、8、9(升序的最新5条,对应limit=5的场景)。
内容的提问来源于stack exchange,提问作者Alex Welander
相关产品推荐
相关产品推荐

