【发布时间】:2019-08-17 23:35:15
【问题描述】:
我有一个数据库记录从 GPS 单元接收到的消息的 unix 时间、纬度和经度。我需要一种方法从该数据库中选择最新的两个条目以在 php 中使用。
示例数据库条目: [3] => stdClass 对象([_id] => MongoDB\BSON\ObjectId 对象([oid] => 5c7fe3fc1c37210bf96e8182)[纬度] => 53.385360717773 [经度] => -6.6032276153564 [时间] => 1551885285))
到目前为止,我只需要一个,我通过搜索最大的时间戳得到了它。有没有办法像在 mySQL 中一样简单地返回 mongo 中的最新两个条目?我注意到“限制”返回第一个条目而不是最后一个条目:
$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"];
}
感谢您的帮助。
编辑:我发现了这个问题How to get the last N records in mongodb?。 mongo 版本不同,但原理似乎很合理:使用 'sort' 然后 'limit'。语法是完全不同的想法我怎么能在这个版本中将两者结合起来?
“db.foo.find().sort({_id:1}).limit(50);”
$options=['limit' => 2];
$filter=[];
$cursor = $collection->find($filter, $options);
【问题讨论】:
标签: mongodb