1

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"?

1 Answers1

1

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\"" } } )
sanyassh
  • 8,100
  • 13
  • 36
  • 70
  • Thank you, that was a precise answer! – Aniruddh Chandratre May 25 '19 at 18:53
  • One more query : If I want to perform a search with "V Neck" as well as "Floral", how should I go about it? There is no guarantee that it will appear as "V Neck Floral" in all matching documents – Aniruddh Chandratre May 25 '19 at 19:00
  • @AniruddhChandratre it seems to be impossible. `$text` cannot be used with `$or` or `$and` and if you specify a phrase with a word like `\"V Neck\" Floral` the word will be ignored. – sanyassh May 25 '19 at 19:11