9

Running the following text search directly on MongoDB results in no issues:

db.getCollection('schools').find({
  $text:
    {
      $search: 'some query string',
      $caseSensitive: false,
      $diacriticSensitive: true
    }
}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})

However when trying to run the same query using the native NodeJS driver:

function getSchools(filter) {
  return new Promise(function (resolve, reject) {

    MongoClient.connect('mongodb://localhost:60001', function(err, client) {
      const collection = client.db('schools').collection('schools');

      collection.find({
        $text:
          {
            $search: filter,
            $caseSensitive: false,
            $diacriticSensitive: true
          }
        }, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}}).toArray(function(err, docs) {
        if (err) return reject(err);

        resolve(docs);
      });
    });
  });
}

I'm getting the following error:

MongoError: must have $meta projection for all $meta sort keys

What am I doing wrong here?

asliwinski
  • 1,662
  • 3
  • 21
  • 38

2 Answers2

21

OK, according to this bug since the version 3.0.0 find and findOne no longer support the fields parameter and the query needs to be rewritten as follows:

collection.find({
        $text:
          {
            $search: filter,
            $caseSensitive: false,
            $diacriticSensitive: true
          }
        })
        .project({ score: { $meta: "textScore" } })
        .sort({score:{$meta:"textScore"}})
asliwinski
  • 1,662
  • 3
  • 21
  • 38
  • 1
    find documentation here: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find – Tien Do Apr 02 '18 at 09:08
  • 3
    So why don't they update the [textScore sort example in their very own documentation](https://docs.mongodb.com/manual/reference/operator/query/text/#sort-by-text-search-score) accordingly?! :rolleyes: Thanks for pointing this out! Probably saved me quite some time, especially because the error message doesn't give a very good hint to the actual error... – Christallkeks Dec 12 '18 at 14:13
  • Hi can anyone tell me if I had to sort in reverse order of the same query? – Sharad Mishra Jun 07 '20 at 06:23
  • @Christallkeks because those are the docs for the mongo shell, the nodejs driver docs are [here](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#find) – benmneb Sep 20 '21 at 04:46
4

In the current version of the native MongoDB driver, you need to include the projection key among the options for find:

const results = await collection.find(
  {
    $text: { $search: filter }
  },
  {
    projection: { score: { $meta: 'textScore' } },
    sort: { score: { $meta: 'textScore' } },
  }
).toArray();
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404