简体   繁体   中英

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. 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. 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

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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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