php - 从 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"];
}
解决方案
通过使用“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");
推荐阅读
- angularjs - ng-checked 不触发 ng-model
- c# - Akka.NET 无法识别我的自定义记录器并默认为 BusLogger
- c++ - 在我的 Arduino 库中使用外部库
- slurm - 如何更改不同分区的默认节点顺序?
- c++ - 带有 std:out_of_range 问题的简单密码 (C++)
- android - 在 FragmentStatePagerAdapter 中移回一个片段时,BringChildToFront() 不起作用
- c# - 选项标签中的多个值
- parsing - 用于构造演算的递归下降解析器
- java - Hibernate JPA 组合键
- tensorflow - 损失随着批量标准化而增加(tf.Keras)