Search with AND operator in MongoDB using $text query operator

I already have text index in MongoDB.

Simple search:

db.news.find({ $text: { $search: "covid" } })

I get all the articles containing covid in the text.

Now I want to get all the articles that contain both covid and vaccination.

This query for example...

db.news.find({ $text: { $search: "\"covid vaccination\"" } })

...will only find articles that contain "covid vaccination" side by side, in that order. In other words, article structured like this: "Vaccination against covid..." will not be found.

I want to find all articles where covid and vaccination are included in the article, regardless of each word position, using the text index. Any ideas?

Upvotes: 0

Views: 172

Answers (1)

Maxim Sharai
Maxim Sharai

Reputation: 614

I re-checked MongoDB documentation and didn't find the way how to do it. May be this will help:

db.news.find({$text: {$search: "covid vaccination"}}).sort({score: {$meta: "textScore"}})

It wouldn't get the required result, but, at least, the result will sorted by score. The records which contains the both "covid" and "vaccination" should be at the top

Upvotes: 1

Related Questions