Search code examples
pythonmongodbfull-text-searchpymongofulltext-index

mongoDB: Full text query for strings containing single letters in PyMongo


I have a collection in MongoDB where-in each document contains title and color. I want to perform a full text search with the title key. For this, I am using the following piece of code :

mycol.create_index([('title', 'text')])
mycol.find({"colors" : color, "$text": {"$search": search_text}}).limit(10)

Now, I want to make a query with the following specification :

{
    'color' : 'blue',
    '$text' : {
         "$search" : "V Neck"
     }
}

This query returns results in which "Neck" as a search text matches but "V" does not appear across the results.

Result on executing the above query:

1. Maniac Men's Fullsleeve Round Neck Round Neck All Over Printed Navy Cotton Tshirt
2. Off White Printed Round Neck Tshirt
3. Blue Striped Round Neck Tshirt
4. Grey Printed Round Neck Tshirt
5. Blue Solid Round Neck Tshirt
6. Blue Solid Round Neck Tshirt
7. Red Printed Round Neck Tshirt
8. Blue Printed Round Neck Tshirt
9. Blue Checked Round Neck Tshirt
10. Grey Printed Round Neck Tshirt

Is there any way to get results which match the entire keyword "V Neck"?


Solution

  • You need to wrap your $search in double-quotes:

    "$search" : "\"V Neck\""
    

    Searching for exact phrases is documented here:

    You can also search for exact phrases by wrapping them in double-quotes. If the $search string includes a phrase and individual terms, text search will only match documents that include the phrase.

    For example, the following will find all documents containing “coffee shop”:

    db.stores.find( { $text: { $search: "\"coffee shop\"" } } )