Search code examples
mongodbmern

MongoDB $text $search returns exact phrase instead of contains


I

I have this data on my local MongoDB and I want to do a search on title field containing "the".

when I used this code it returned an empty array:

postsArray = await posts.find({ $text: { $search: "the" } }).toArray()

However if I entered the exact title, it returned the correct result

postsArray = await posts.find({ $text: { $search: "the game" } }).toArray()

according to the documentation, the first code should also return the same result,

Any idea why this happens?

Thanks


Solution

  • The $text search will not match the and and words, There is an instruction about Match Operation:

    Stop Words:

    The $text operator ignores language-specific stop words, such as the and and in English.


    Let's take an example of different words and it should work:

    Assume we have the below document:

    { "title": "Good Morning" }
    

    Query 1: Search for "good" word:

    { $text: { $search: "good" } }
    

    Result: Playground

    { "title": "Good Morning" }
    

    Query 2: Search for "good morning" word:

    { $text: { $search: "good morning" } }
    

    Result: Playground

    { "title": "Good Morning" }