Php 如何从mongodb按日期排序输出数据集合
我想从mongodb检索10行最新新闻。 首先,我需要按字段“timestamp”按升序对数据进行排序。然后我需要选择前10行,它们是具有最新时间戳的行。 这就是我(成功)建立连接的方式 这就是我按照PHP手册指南获取数据的方法Php 如何从mongodb按日期排序输出数据集合,php,mongodb,Php,Mongodb,我想从mongodb检索10行最新新闻。 首先,我需要按字段“timestamp”按升序对数据进行排序。然后我需要选择前10行,它们是具有最新时间戳的行。 这就是我(成功)建立连接的方式 这就是我按照PHP手册指南获取数据的方法 $cursor->sort(array('timestamp' => 1)); foreach($cursor as $doc){ echo $doc["title"]; } 仅供参考:时间戳的数据类型为字符串:“2015/01/31”。我
$cursor->sort(array('timestamp' => 1));
foreach($cursor as $doc){
echo $doc["title"];
}
仅供参考:时间戳的数据类型为字符串:“2015/01/31”。我不确定这是否是原因
另外,当我使用MySql进行php时,浏览器总是告诉我问题出在哪一行。使用mongodb,除了空白页之外,它不会给您任何错误报告。…php语法有点混乱 可以在
find
上执行Sort()
和Limit()
方法(无论排序顺序如何,排序总是先进行)
它看起来像这样:
$cursor = $collection->find ()->sort(array('timestamp'=>-1))->limit(10);
$filter = [];
$options = ['sort' => ['timestamp' => -1]];
$client = new MongoDB\Client('mongodb://localhost');
$client->mydb->mycollection->find($filter, $options);
$cursor=$collection->find()->排序(数组('timestamp'=>-1))->限制(10);
然后您可以在php中颠倒10个文档的顺序,或者您可能需要使用聚合框架。排序不再像这样工作, 为了能够使用find进行排序,只需使用第二个find参数,如下所示: $cursor = $collection->find ()->sort(array('timestamp'=>-1))->limit(10);
$filter = [];
$options = ['sort' => ['timestamp' => -1]];
$client = new MongoDB\Client('mongodb://localhost');
$client->mydb->mycollection->find($filter, $options);
复制自您可以使用_id字段按时间戳排序 以下查询可以打印最近10条记录
$cursor = $collection->find()->sort( array("_id" => -1 ))->limit(10);
非常感谢。所以'timestamp'=>-1表示最近的日期,'timestamp'=>1表示最早的日期?是的,1是升序,而-1是降序。如果在Mongodb中时间戳是简单的整数,为什么不呢?