How to AND and NOT in MongoDB $text search

后端 未结 1 1935
Happy的楠姐
Happy的楠姐 2020-12-17 02:19

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

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 03:13

    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.

    0 讨论(0)
提交回复
热议问题