Home > Software engineering >  PHP - MongoDB find the latest records, but order Descending
PHP - MongoDB find the latest records, but order Descending

Time:02-01

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.

CodePudding user response:

$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']);
});

CodePudding user response:

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);
  •  Tags:  
  • Related