I have just shifted from the old Mongo extension to the newest PHP driver (mongodb). I'm also using the PHP library provided for mongodb.
Previously, I could simply do ->sort()
on a cursor instance, but that doesn't seem to be the case any more since I get this error:
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::sort()
What is the alternative to sorting/limiting/skipping now?
To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
If MongoDB cannot obtain the sort order via an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first k results (or last, depending on the sort order) seen so far by the underlying index or collection access.
Sort by Value To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.
I got an answer about this on the respective Github repository.
To be able to sort with find
, you simply use the second find
parameter like this:
$filter = [];
$options = ['sort' => ['username' => 1]];
$client = new MongoDB\Client('mongodb://localhost');
$client->mydb->mycollection->find($filter, $options);
For more information, look into the issue I have posted at the repository:
https://github.com/mongodb/mongo-php-driver/issues/214
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With