Stop mongodb from ignoring special characters?

前端 未结 1 1867
一个人的身影
一个人的身影 2021-01-25 07:25
Model.find({ $text : {$search: \"#text\"} })

returns everything that includes \"text\", not only those documents with \"#text\". I\'ve tried putting an

相关标签:
1条回答
  • 2021-01-25 07:44

    Tomalak's description of how text indexing works is correct, but you can actually use a text index for an exact phrase match on a phrase with a special character:

    > db.test.drop()
    > db.test.insert({ "_id" : 0, "t" : "hey look at all this #text" })
    > db.test.insert({ "_id" : 1, "t" : "text is the best" })
    > db.test.ensureIndex({ "t" : "text" })
    
    > db.test.count({ "$text" : { "$search" : "text" } })
    2
    > db.test.count({ "$text" : { "$search" : "#text" } })
    2
    
    > db.test.find({ "$text" : { "$search" : "\"#text\"" } })
    { "_id" : 0, "t" : "hey look at all this #text" }
    

    Exact phrase matches are indicated by surrounding the phrase in double quotes, which need to be escaped in the shell like "\"#text\"".

    Text indexes are larger than normal indexes, but if you are doing a lot of case-insensitive exact phrase matches then they can be a better option than a standard index because they will perform better. For example, on a field t with an index { "t" : 1 }, an exact match regex

    > db.test.find({ "t" : /#text/ })
    

    performs a full index scan. The analogous (but not equivalent) text query

    > db.test.find({ "$text" : { "$search" : "\"#text\"" } })
    

    will use the text index to locate documents containing the term "text", then scan all those documents to see if they contain the full phrase "#text".

    Be careful because text indexes aren't case sensitive. Continuing the example above:

    > db.test.insert({ "_id" : 2, "t" : "Never seen so much #TEXT" })
    
    > db.test.find({ "t" : /#text/ })
    { "_id" : 0, "t" : "hey look at all this #text" }
    
    > db.test.find({ "$text" : { "$search" : "\"#text\"" } })
    { "_id" : 0, "t" : "hey look at all this #text" }
    { "_id" : 2, "t" : "Never seen so much #TEXT" }
    
    0 讨论(0)
提交回复
热议问题