简体   繁体   English

查找和排序查询 PHP MONGODB

[英]Find and Sort Query PHP MONGODB

I'm currently trying to display a query in which I'm trying to sort by a specific column ("epoch_start").我目前正在尝试显示一个查询,其中我试图按特定列(“epoch_start”)进行排序。

For some reason, I'm able to display the query by using the find() function but whenever I try to use the sort() function, I receive the following error:出于某种原因,我可以使用 find() 函数显示查询,但是每当我尝试使用 sort() 函数时,我都会收到以下错误:

Uncaught Error: Call to undefined method MongoDB\\Driver\\Cursor::sort()未捕获的错误:调用未定义的方法 MongoDB\\Driver\\Cursor::sort()

Please find my code below:请在下面找到我的代码:

<?php

$query2 = array('complete_title' => array('$regex' => 'andrew_marr'));

$cursor = $collection_programs
->find($query2)
->sort(array("epoch_start" => 1));

foreach ($cursor as $doc) {

?>

<tr>
  <td><?php echo $doc["pid"] ?></td>
  <td><?php echo $doc["start_time"] ?></td>
  <td><?php echo $doc["end_time"] ?></td>
  <td><?php echo $doc["complete_title"] ?></td>
  <td><?php echo $doc["media_type"] ?></td>
  <td><?php echo $doc["masterbrand"] ?></td>
  <td><?php echo $doc["service"] ?></td>
   <td><?php echo $doc["masterbrand"] ?></td>
</tr>

<?php
}
 ?>

Please can somebody advise?请问有人可以建议吗?

I haven't used PHP with MongoDB for the last year but there you have an error because you use sort in a cursor component and the documentation said that you can use sort as an option in query component.去年我没有将 PHP 与 MongoDB 一起使用,但是出现错误,因为您在游标组件中使用了排序,并且文档说您可以在查询组件中使用排序作为选项。

Try with this code, I didn't check but if you are using MongoDB Driver maybe work fine.尝试使用此代码,我没有检查,但如果您使用的是 MongoDB 驱动程序,则可能工作正常。

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$filter = ['complete_title' => ['$regex' => 'andrew_marr']];
$options = ['sort' => ['epoch_start' => 1]];
$query = new MongoDB\Driver\Query( $filter, $options );

$cursor = $manager->executeQuery("your_collection", $query);

foreach($cursor as $document) {
    print_r($document);
}

Another option that I just read我刚刚阅读的另一个选项

$query = new MongoDB\Driver\Query( $filter );

$cursor = $manager->executeQuery("your_collection", $query);
$cursor->sort(['epoch_start' => 1]);

foreach($cursor as $document) {
    print_r($document);
}

Also, you can use the code without filter and check if the results are ordered.此外,您可以使用不带过滤器的代码并检查结果是否已排序。

Regards!问候!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM