Mongo - 根据'ts'(时间戳)获取第一个创建和最后创建的文档

Rah*_*hul 1 php mongodb

是否可以根据单个mongo查询中文档的'ts'(timestamp)元素获取第一个创建的文档和最后创建的文档?如果是,那么请让我知道如何使用PHP查询mongo.

jar*_*red 8

您无法在一个查询中获取它们,但您可以在2个查询中执行此操作.

db.collection.find().limit(1).sort([ts:-1])  --> Find the last timestampe
db.collection.find().limit(1).sort([ts:1])   --> Find the first timestamp 
Run Code Online (Sandbox Code Playgroud)

或者在PHP中

$cursor = $collection->find()->sort(array('ts'=>-1))->limit(1);
$cursor = $collection=>find()->sort(array('ts'=>1))->limit(1);
Run Code Online (Sandbox Code Playgroud)

  • Mongo中的查询应该是:`db.collection.find().limit(1).sort({ts:-1}) - >查找最后一个时间戳`和`db.collection.find().limit( 1).sort({ts:1}) - >查找第一个时间戳 (3认同)