Reputation: 142
I have a database in MongoDB users
. It contains following fields:
I tried to concatenate the first name (fname) and last name (lname) through aggregate function with the following php code.
$cursor = $this->users->aggregate(
array(
'$project' => array(
'name' => array('$concat' => array('$fname', ' ', '$lname'))
)
)
);
This seems to work fine. But How do we sort the results? I tried to use this line of code to sort the result
$cursor->sort(array("name" => 1));
But this give me the following error:
Fatal error: Call to a member function sort() on array
However, I tried to use this code in console and it worked fine:
db.users.aggregate({
$project: {
'name' {$concat: ['$fname', ' ', '$lname']}
}
}, {$sort: {name: 1}});
This code worked nicely and I get the result in sorted manner.
What might be the problem with sort function in php code?
Any help would be appreciated.
Upvotes: 2
Views: 1620
Reputation: 715
Try this code:
$cursor = $this->users->aggregate(
array(
'$project' => array(
'name' => array('$concat' => array('$fname', ' ', '$lname'))
)
),array(
'$sort' => array(
'name' => 1
)
)
);
Hope this help.
Upvotes: 2