I apologise in advance if this question has been asked, I searched without finding an answer.
I want to do a search in MongoDB, and I create the index and do somethi
There are a few options that you can use with text search to suit those needs. Consider the following documents:
{ "text" : "cake" }
{ "text" : "sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale" }
{ "text" : "dress sale" }
{ "text" : "cake sale monday" }
The default "list" of words is an or inclusion, but if you wan't an and inclusion you "quote" the words:
db.words.find( { "$text": { "$search": "\"cake\" \"sale\"" } },{_id: 0})
{ "text" : "cake sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale monday" }
If you want to exclude a word then you prefix with -
:
db.words.find( { "$text": { "$search": "\"cake\" \"sale\" -monday" } },{_id: 0})
{ "text" : "cake sale" }
{ "text" : "sale cake" }
And if you wanted part of that as an exact phrase then you "quote" the whole phrase:
db.words.find( { "$text": { "$search": "\"cake sale\" -monday" } },{_id: 0})
{ "text" : "cake sale" }
Stemming words though does have an issue, so :
db.words.find( { "$text": { "$search": "test -testing" } },{_id: 0})
Would not actually return a result.
See the documentation on the $text operator for examples. Not all are there at the moment, but it's getting better.