MongoDB Atlas search: sort by "searchScore"

Viewed 1258

I run the following aggregation pipeline and it works well:

[
  {
    $search: {
      text: {
        query: text,
        path: 'name',
        fuzzy: {
          maxEdits: 2,
          prefixLength: 0,
          maxExpansions: 256,
        },
      },
    },
  },
  {
    $limit: 10,
  },
  {
    $project: {
      _id: 1,
      name: 1,
      score: { $meta: 'searchScore' },
     },
  },
]

I can see that the score-field is present in my result and is correct. Now I want to sort the documents retrieved by the $meta-property searchScore. However, adding this step at the end of the pipeline:

{
  $sort: { score: { $meta: 'searchScore' }, _id: 1 },
}

Yields the following error:

MongoError: $meta sort by 'searchScore' metadata is not supported

How do I achieve this?

1 Answers

You need to add a new field that contains the result of $meta before sorting (which you already do) and then sort on that field, so you new pipeline would be:

...

{
    $project: {
      _id: 1,
      name: 1,
      score: { $meta: 'searchScore' }, // you are already adding the field here.
     },
},
{
   $sort: {
      score: -1, // use the new computed field here.
      _id: 1
   }
}
Related