Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sorting work in the new mongodb PECL extension?

Tags:

php

mongodb

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?

like image 866
aborted Avatar asked Feb 02 '16 07:02

aborted


People also ask

How does MongoDB sorting work?

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.

What sorting algorithm does MongoDB use?

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.

How do I sort an array in MongoDB?

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.


1 Answers

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

like image 185
aborted Avatar answered Oct 21 '22 03:10

aborted