我有一个mongo集合,我想获取所有名称以PHP上的给定字母开头的文档。我的代码:
$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);
我使用查询1.我收到所有以字母c开头但未订购的文件。当我使用查询2时,我什么也没得到。最后,当我使用查询3时,我几乎得到了每个文档,而不仅仅是那些以'c'开头的文档。我在这里做错了什么?
答案 0 :(得分:1)
mongo
方法sort
应该在cursor
获得的find
上应用{/ 1}}
$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);