i need to find the most recent element, the field "data_caricamento" save the date. so i made a index with MognoDb shell:
db.collection.ensureIndex({"data_caricamento": -1})
and with the php code below i have what i need
$cursor=$collection->find();
$cursor->sort(array("data_caricamento"=> -1));
$cursor->limit($n);
but i think that should be a better way to do it, for example there is a way to query the directly the index? thx.
there is a way to query the directly the index?
Sort of. You can do a covered query here by doing:
$cursor = $collection
->find(array(), array('_id' => 0, 'data_caricamento' => 1))
->sort(array("data_caricamento" => -1))
->limit($n);
That will query only the index.
Try using the hint. And if you want to check whether the indexes got used by your query use explain().
....
$collection->find()->sort(array('data_caricamento'=>1))->hint(array('data_caricamento'=>1));
print_r($cursor->explain());
This will help you see that your queries are hitting index for faster search and sorting! Cheers!