user3052997
user3052997

Reputation: 91

how to sort with mongodb php

I've tried a number of variations to get mongodb php to sort by score decending. It won't do it.

here's my script

  $dd=array('gameID'=>(int)$gameID);
  $s=array( 'score' => -1);
  $cursor = $collectiontsWon->find($dd)->sort($s)->limit(7)->skip(0);

Everything is right, this is like the 8 variation of sort I've used. But it's NOT sorting by score decending on my site. What am I doing wrong?

Upvotes: 0

Views: 2121

Answers (2)

Mukul Mantosh
Mukul Mantosh

Reputation: 368

<?php

$cursor->sort(array('x' => 1)); // Sort on field x, ascending

// The order in the associative array is important. For instance, these two // examples will yield different results:

$cursor->sort(array('date' => 1, 'age' => -1)); // Sort on date ascending and age descending

$cursor->sort(array('age' => -1, 'date' => 1)); // Sort on age descending and date ascending

?>

Upvotes: 0

Hassan
Hassan

Reputation: 626

Try setting the cursor, then sorting the data

$cursor = $mongo->collection->find()->limit(7);

$cursor = $cursor->sort(array("score" => -1));
foreach($cursor as $doc) {
    // Do something...
}

Also, I don't think you need to explicitly set skip to 0.

Upvotes: 1

Related Questions