Naumov Naumov - 4 months ago 30
PHP Question

Mongodb cursor method sort [fixed]

/**
* @param $key
* @param $value
* @param $collection
* @return array | \MongoDB\Driver\Cursor
*/
static function simpleSelect($key, $value, $collection)
{
$con = \Core\Model\Mongo::getConnect();

$query = new \MongoDB\Driver\Query(
array(
$key => $value
)
);

return $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
}


I develop class, for mongodb driver. And I have trouble, how to I can call function
sort
for mongoDB, for example https://docs.mongodb.com/manual/reference/method/cursor.sort/ in this documentation I read what
cursor
have
sort
but in php
\MongoDB\Driver\Cursor
class don't have
sort
method...

I fixed this by modified my code

/**
* @param $key
* @param $value
* @param $collection
* @return array | \MongoDB\Driver\Cursor
*/
static function simpleSelect($key, $value, $collection)
{
$con = \Core\Model\Mongo::getConnect();

$query = new \MongoDB\Driver\Query(
array(
$key => $value
),
array('sort' => array('time' => -1))
);

return $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
}


method query have 2 parameters, options this is array can contain sort, ordered and other options for collection. But this is not finish code because I whant create new method for set sorting and other option...

p.s. I'm sorry for my English.

Answer

In PHP the syntax used to sort a Mongodb collection is

// Sort on field x, ascending 
$cursor->sort(array('x' => 1));

Your code can be modified to :-

static function simpleSelect($key, $value, $collection)
{
    $con = \Core\Model\Mongo::getConnect();

    $query = new \MongoDB\Driver\Query(
        array(
            $key => $value
        )
    );
    $cursor = $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
   $cursor->sort(array('x' => 1));
   return $cursor;
}