0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

but still sort even if the index is yet sorted. so the complexity not changed
@user3535936 wehat do you mean? The index is already sorted, your just reading from the place in the index
but on your code still have 3 command on the pipe find->sort->limit so i ask myself if it will improve performance
@user3535936 yes all I have done is added projection to let MongoDB know what it needs to pick out allowing it to say: "I don't need to look at the records to know what to pick"
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.