Reputation: 691
How would I go about using an answer like this one in F3?
php mongodb full-text search and sort
EDIT:
I am searching in a title and description. If there is no searchterm it will sort on a field created_at
. If there is a searchterm however: sort it on the most relevant.
EDIT: EDIT: I am also using the pagination plugin if that matters.
Upvotes: 1
Views: 1995
Reputation: 3908
Using the edge version of the framework, you'll be able to define a projected field named score
and use it for sorting.
E.g:
// MongoDB instance
$db=new DB\Mongo('localhost:27017','mydb');
// Define a `score` field here
$fields=['score'=>['$meta'=>'textScore']];
// Mapper instance
$mapper=new DB\Mongo\Mapper($db,'mycollection',$fields);
// Search text and sort by score
$mapper->load(
['$text'=>['$search'=>'search text']],
['order'=>['score'=>['$meta'=>'textScore']]]
);
Upvotes: 3
Reputation: 447
Use the aggregation framework to get the documents that have most relevant text score by doing a $match
pipeline operation which will match the search term, followed by a $project
operator pipeline which projects the score fields, and then do another $order
pipeline operation to return most relevant item. The "textScore" metadata is available for projections, sorts, and conditions subsequent the $match
stage that includes the $text
operation:
db.collection.aggregate([
{
"$match": {
"$text": {
"$search": "search text"
}
}
},
{
"$project": {
"_id": 0,
"score": {
"$meta": "textScore"
}
}
},
{
"$orderby": {
"score" : -1
}
}
])
Upvotes: 1