Jay.F
Jay.F

Reputation: 101

Return latest 2 entries from a mongo database?

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

Upvotes: 0

Views: 55

Answers (2)

Jay.F
Jay.F

Reputation: 101

Got it to work with:

 $options = ['sort' => ['Time' => -1], 'limit' => 2];
  $filter=[];
  $cursor = $collection->find($filter, $options);

Upvotes: 0

Anirudh Simha
Anirudh Simha

Reputation: 360

Keep extending the query as follows:

$cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)

Upvotes: 1

Related Questions