0

I have a database recording the unix time, latitude and longitude of a received message from a GPS unit. I need a way to select the latest two entries from this database to work with in php.

Example database entry: [3] => stdClass Object ( [_id] => MongoDB\BSON\ObjectId Object ( [oid] => 5c7fe3fc1c37210bf96e8182 ) [Latitude] => 53.385360717773 [Longitude] => -6.6032276153564 [Time] => 1551885285 ) )

So far I only needed one and I got it by searching for the largest timestamp. Is there a way to simply return the latest two entries in mongo like in mySQL? I've noticed 'limit' returns the first entries not the last:

  $options=['limit' => 2];
  $filter=[];
  //$cursor = $collection->find($filter, $options);
  $cursor = $collection->find($filter);
    $largest =  0;
   foreach($cursor as $document){
   if ($largest < $document["Time"]) {
       $largest = $document["Time"];
       $longitude = $document["Longitude"];
       $latitude = $document["Latitude"];
   }

Thanks for any help.

edit: I've found this question How to get the last N records in mongodb?. The mongo version is different but the principle seems sound: use 'sort' then 'limit'. The syntax is quite different thought how could I combine the two in this version?

"db.foo.find().sort({_id:1}).limit(50);"

  $options=['limit' => 2];
      $filter=[];
      $cursor = $collection->find($filter, $options);
Jay.F
  • 101
  • 9

2 Answers2

1

Keep extending the query as follows:

$cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)
Anirudh Simha
  • 340
  • 1
  • 8
  • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help! – Jay.F Mar 27 '19 at 12:22
0

Got it to work with:

 $options = ['sort' => ['Time' => -1], 'limit' => 2];
  $filter=[];
  $cursor = $collection->find($filter, $options);
Jay.F
  • 101
  • 9