停止mongodb忽略特殊字符? [英] Stop mongodb from ignoring special characters?
问题描述
Model.find({ $text : {$search: "#text"} })
返回所有包含文本"的内容,不仅返回那些带有"#text"的文档.我尝试将\放在#前面,但无济于事.如何阻止mongodb忽略我的特殊字符?谢谢.
returns everything that includes "text", not only those documents with "#text". I've tried putting an \ before the #, to no avail. How do I stop mongodb from ignoring my special characters? Thanks.
推荐答案
Tomalak关于文本索引工作原理的描述是正确的,但是您实际上可以将文本索引用于
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" }
精确的词组匹配通过用双引号括住该词组来指示,该词组需要像"\"#text\""
这样在外壳中转义.
Exact phrase matches are indicated by surrounding the phrase in double quotes, which need to be escaped in the shell like "\"#text\""
.
文本索引比普通索引大,但是如果您执行很多不区分大小写的精确短语匹配,则它们比标准索引更好,因为它们会表现更好.例如,在具有索引{ "t" : 1 }
的字段t
上,一个完全匹配的正则表达式
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\"" } })
将使用文本索引查找包含术语""text"
"的文档,然后扫描所有这些文档以查看它们是否包含完整的短语""#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" }
这篇关于停止mongodb忽略特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!