MongoDB error- must have $meta projection for all $meta sort keys while performing text search in NodeJS


I'm using the below query to perform text search in NodeJS, to sort the MongoDB results in order of relevance score:

db.getCollection('posts').find({ $text: { $search: "search string"} },{ score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } ).toArray();

I'm getting MongoDB error- must have $meta projection for all $meta sort keys but when i query on MongoDB directly it is working fine. What's wrong here?

1 Answer

4 years ago by

In the recent versions of native MongoDB Driver, you need to include project option instead of specifying parameters to find and findOne query as shown below.

 db.collection('posts').find({ $text: { $search: "search string"} }).project({ score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } ).toArray();
4 years ago by Jahaan