Search code examples
phpmongodbfat-free-framework

Full text search and score sorting MongoDB


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.


Solution

  • 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']]]
    );