Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this mongo sort not working in PHP?

Tags:

php

mongodb

I'm following an example from the 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);
    }

Doing this, I see the documents in a random order (not sorted).

But executing this query from the mongo console produces a correctly sorted response:

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

I feel like there must be something obvious I'm missing.

like image 387
justkevin Avatar asked Apr 24 '13 17:04

justkevin


1 Answers

I think I see the problem. Instead of doing this:

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

Try this:

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

Easy mistake to make, but very frustrating to find if you don't see it right away.

like image 118
Tim Gautier Avatar answered Nov 07 '22 20:11

Tim Gautier