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

时间:2011-02-28 09:46:44

标签: php mongodb

是否可以根据单个mongo查询中文档的'ts'(timestamp)元素获取第一个创建的文档和最后创建的文档? 如果是,请告诉我如何使用php查询mongo。

1 个答案:

答案 0 :(得分: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 

或在PHP中

$cursor = $collection->find()->sort(array('ts'=>-1))->limit(1);
$cursor = $collection=>find()->sort(array('ts'=>1))->limit(1);