1

I have a mongo collection and I'd like to obtain all the document whose names start with a given letter on PHP. My code:

$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");     
$regex = new MongoDB\BSON\Regex  ("^$letter", "i"); 
$query = array('name' =>  $regex); // 1
$query = array('name' =>  $regex, array( 'sort' => array( 'OrderBy' => 1 ) )); // 2
$query = new MongoDB\Driver\Query( array('name' => $regex), array( 'sort' => array( 'OrderBy' => 1 ) ) ); // 3
$cursor = $pme->find($query);

Whe I use query 1. I got all documents starting with letter c but not ordered. When I use query 2, I got nothing. And finally when I use query 3 I get almost every document, not just those starting with with 'c'. What I am doing wrong here?

1 Answer 1

1

In mongo method sort should be applied on cursor obtained by find:

$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");     
$regex = new MongoDB\BSON\Regex  ("^$letter", "i"); 
$query = array('name' =>  $regex);
// sort by field `name` happens here
$options = array("sort" => array("name" => 1), );
$cursor = $pme->find($query, $options);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but the sort method of cursor no longer exist.
I've updated answer. Pls see github.com/mongodb/mongo-php-driver/issues/214 for details.
Thanks Mike, I was about to publish exactly this solution. I works now.

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.