Why is this type of mongo not working in PHP?

I am following an example from PHP docs to sort some records in a collection:

$cursor = $mongo->party_scores->find()->limit(10); $cursor = $cursor->sort(array("score",-1)); foreach($cursor as $doc) { print_r($doc); } 

By doing this, I see documents in random order (not sorted).

But executing this request from the mongo console results in a properly sorted answer:

 db.party_scores.find().sort({score : -1 }) 

I feel that there must be something obvious that I am missing.

+6
source share
1 answer

I think I see a problem. Instead of this:

 $cursor->sort(array("score",-1)) 

Try the following:

 $cursor->sort(array("score" => -1)) 

A simple mistake, but very difficult to find if you do not see it right away.

+13
source

Source: https://habr.com/ru/post/943564/


All Articles