Happydevdays Happydevdays - 4 months ago 8
PHP Question

mongo db - can't get right syntax to sort documents by a specific field

I have the following php code that works:

global $m, $db;
$collection = $db->locations;
try{
$cursor = $collection->find();
return $cursor;
} catch(MongoCursorException $e) {
return false;
}


Now I'd like to sort the results in ascending order by a field called "name".

This is what I've tried:

global $m, $db;
$collection = $db->locations;
try{
$cursor = $collection->find().sort({name:1});
return $cursor;
} catch(MongoCursorException $e) {
return false;
}


But I'm getting an error that says:

Parse error: syntax error, unexpected '{' in /var/www/html/myapp/models/locations_model.php on line 23


Any tips?

Answer

Try

$cursor = $collection->find()->sort(['name' => 1]);

Your error is because you are not sending an array to the sort, which it expects, see PHP mongocursor sort

Comments