David Gorgan
David Gorgan

Reputation: 31

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").

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:

Uncaught Error: Call to undefined method 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?

Upvotes: 1

Views: 1564

Answers (1)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

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.

Try with this code, I didn't check but if you are using MongoDB Driver maybe work fine.

$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!

Upvotes: 1

Related Questions