1

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.

Bilbonic
  • 225
  • 1
  • 2
  • 7
  • 1
    I think this can help you out https://stackoverflow.com/questions/4421207/how-to-get-the-last-n-records-in-mongodb – Segun Adeniji Jan 30 '22 at 23:29
  • Why not use the PHP built-in [`array_reverse`](https://www.php.net/manual/en/function.array-reverse.php) function on the result? – Moshe Katz Jan 30 '22 at 23:42
  • @Moshe Katz, I tried that and had no luck. Kept getting an error for passing an object instead of an array. – Bilbonic Jan 31 '22 at 05:46
  • @SegunAdeniji That post definitely pointed me in the right direction. I made a work around that worked for me using the skip parameter. Thanks! – Bilbonic Jan 31 '22 at 05:48

2 Answers2

0
$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']);
});
Segun Adeniji
  • 370
  • 5
  • 11
0

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);
Bilbonic
  • 225
  • 1
  • 2
  • 7