MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Sort full and partial word search by textScore

I am using the $text operator to $search for a specific string, for example, ‘Rob’ then sort by textScore the results from this search query.

My issue is that when the search string is ‘Rob’ it will only return documents with the word Rob in it BUT when the search string is ‘Ro’ it returns no users.

I found semi-solutions to where I use the $match operator with regex but unfortunately, to my knowledge, I cannot use textScore to sort the results.

My question is, how can I do a full and partial word search and sort the results by the relevancy of the result or by textScore.

    UserDB.userModel.find({
      $text:{
        $search: "ah",
        $caseSensitive: false,
        $diacriticSensitive: true
      }
    },
      {score : { $meta: "textScore" } } 
).sort( { score: { $meta: "textScore" } } )

$match semi-solution

    {$match: {$or: [
        {'username': regex},
        {'name.first': regex},
        {'name.last': regex}
      ]}}