首页 > 解决方案 > 从 mongodb find() 结果中获取变量

问题描述

我有一个 mongodb find() ,它可以让我获得数据库中的两个最新条目,以便在我的 php 代码中使用。到目前为止,我只需要处理一个条目,下面是从最新条目中获取时间戳、纬度和经度变量的代码。

谁能建议为第二个条目获取相同变量的最佳方法?我尝试使用“$document[0]”像数组一样访问,但我认为它是按名称键控的。谢谢你的帮助!

    //sort in descending order (time), pick first 2 entries
    $options = ['sort' => ['Time' => -1], 'limit' => 2];
    $filter=[];
    $cursor = $collection->find($filter, $options);

    //get the latest entry (biggest unix timestamp)
    $largest =  0;
    foreach($cursor as $document){
       if ($largest < $document["Time"]) {
       $largest = $document["Time"];
       $longitude = $document["Longitude"];
       $latitude = $document["Latitude"];
        }

标签: phpmongodb

解决方案


通过使用“skip 1”重复所有内容,但没有其他任何内容,想出了一种不优雅的方式:

$options = ['sort' => ['Time' => -1], 'limit' => 2, 'skip' => 1];
  $cursor = $collection->find($filter, $options);
  //initialize variables containing the previous entry data
  $largest2 =  0;
  foreach($cursor as $document){
   if ($largest2 < $document["Time"]) {
       $largest2 = $document["Time"];
       $longitude2 = $document["Longitude"];
       $latitude2 = $document["Latitude"];
        }
}
  echo  nl2br ("\n previous entry");
  echo  nl2br ("\n $latitude2");
  echo  nl2br ("\n $longitude2");
  echo  nl2br ("\n $largest2");

推荐阅读