按升序获取最后N个条目

时间:2018-05-16 23:54:06

标签: php mongodb

如何在PHP中按升序从MongoDB中获取最后N个条目?

这是我现在正在使用的代码,它为我提供了最后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;

$filter  = [];
$options = ['sort' => ['time_stamp' => -1], 'limit' => 60];

$show = $trafico_total->find($filter, $options);

foreach ($show as $collection) {
    $json[]= [strtotime($collection["time_stamp"])*1000, (int)$collection["tx"], (int)$collection["rx"]];
}
    echo json_encode($json);

?>

例如,如果我有时间戳的行:1,2,3,4,5,6,7,8,9。我希望结果显示为5,6,7,8,9而不是9,8,7,6,5

1 个答案:

答案 0 :(得分:1)

如果只是相对较少的结果,你没有“分页”(即使用limitskip),那么最有效的操作就是简单地“反转”返回的结果将从MongoDB\Driver\Cursor返回的MongoDB\Collection::find()转换为“数组”。

这是驱动程序的Cursor->toArray()方法,以及array_reverse()作为标准PHP函数。

$filter  = [];
$options = ['sort' => ['time_stamp' => -1], 'limit' => 60];
$show = array_reverse($trafico_total->find($filter, $options)->toArray());

然后,当你迭代列表时,结果是按升序排列的,是光标返回它们的“反向”。

或者您可以使用aggregate()

$show = $tracfico_total->aggregate([
  [ '$match' => [] ],
  [ '$sort' => ['time_stamp' => -1 ] ],
  # [ '$skip' => $itemsInPage ],
  [ '$limit' => 60 ],
  [ '$sort' => ['time_stamp' => 1 ] ]
]);

在应用限制之前,通常会$skip通过之前的结果,然后重新排序最终输出。但它确实没有增加常规查询已经做的事情,而常规查询可能会更有效地做到这一点。

通常没有必要要求数据库执行实际上“减少”要返回的结果的事情,因此除非您在服务器上执行其他操作,否则通常不会在服务器上执行此操作结果减少了要归还的内容。

另一种情况通常是“大结果集”,它更适合迭代游标。在这种情况下,建议使用聚合方法,而不是将光标转换为“在内存中”的数组,而不是简单地按返回的顺序迭代结果。

相关问题