PHP优化mongodb排序查询


php mongodb optimization sort query

我需要找到最近的元素,字段"data_caricamento"保存日期。所以我用MognoDb shell做了一个索引:

db.collection.ensureIndex({"data_caricamento": -1})

和下面的PHP代码,我有我需要的

$cursor=$collection->find();
    $cursor->sort(array("data_caricamento"=> -1));
    $cursor->limit($n);  

但我认为这应该是一个更好的方法,例如有一种方法可以直接查询索引吗?thx .

有办法直接查询索引吗?

。您可以执行以下命令执行覆盖查询:

$cursor = $collection
    ->find(array(), array('_id' => 0, 'data_caricamento' => 1))
    ->sort(array("data_caricamento" => -1))
    ->limit($n);

只查询索引

尝试使用提示。如果您想检查查询是否使用了索引,请使用explain()。

....
$collection->find()->sort(array('data_caricamento'=>1))->hint(array('data_caricamento'=>1));
print_r($cursor->explain());

这将帮助您看到您的查询正在命中索引,以便更快地搜索和排序!干杯!