简体   繁体   English

PHP - MongoDB 找到最新记录,但顺序降序

[英]PHP - MongoDB find the latest records, but order Descending

I am trying to grab 20 of the most recent records from my database, but then order them descending.我试图从我的数据库中获取 20 条最新记录,然后按降序排列。 I am not sure if this is even possible.我不确定这是否可能。 Here is what i have and what my results have been:这是我所拥有的以及我的结果:

$options = ['limit'=>20, 'sort'=>['creation_date'=>-1]];
$result = $db->find(['_id'=> new \MongoDB\BSON\ObjectID($group_id)], $options);

returns 20 newest records, but in ascending order.返回 20 条最新记录,但按升序排列。 I want these records, but reversed我想要这些记录,但是颠倒了

$options = ['limit'=>20, 'sort'=>['creation_date'=>1]];
$result = $db->find(['_id'=> new \MongoDB\BSON\ObjectID($group_id)], $options);

returns 20 records in the correct descending order, but it is the oldest 20 records以正确的降序返回 20 条记录,但它是最旧的 20 条记录

I am probably missing something simple here, but any suggestions would be greatly appreciated.我可能在这里遗漏了一些简单的东西,但任何建议都将不胜感激。

$options = ['limit'=>20, 'sort'=>['creation_date'=>-1]];
$result = $db->find(['_id'=> new \MongoDB\BSON\ObjectID($group_id)], $options);

$sortedResult = usort($result, function($a, $b) {
    return strtotime($a['creation_date']) - strtotime($b['creation_date']);
});

Alright.好吧。 Thanks to @SegunAdeniji, I was able to make something work.感谢@SegunAdeniji,我能够做一些事情。 Here is the solution I came up with.这是我想出的解决方案。

//counting the total records for the query
$count = $db->count(['_id'=> new \MongoDB\BSON\ObjectID($group_id)]);
//get a count of how many records need to be emitted
$skip_count = $count - 20;
//instead of using limit=20, the skip emits everything beyond 20 records
$options = ['sort'=>['creation_date'=>1], 'skip'=>$skip_count];
$result = $db->find(['_id'=> new \MongoDB\BSON\ObjectID($group_id)], $options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM