阻止 mongodb 忽略特殊字符?
Stop mongodb from ignoring special characters?
Model.find({ $text : {$search: "#text"} })
returns 包含 "text" 的所有内容,而不仅仅是带有“#text”的那些文档。我试过在 # 前加一个 \,但没有用。如何阻止 mongodb 忽略我的特殊字符?谢谢。
Tomalak 对文本索引工作原理的描述是正确的,但实际上您可以对具有特殊字符的短语 exact phrase match 使用文本索引:
> 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" }
精确短语匹配用双引号括起短语表示,需要在 shell 中转义,如 "\"#text\""
.
文本索引比普通索引大,但如果您要进行大量不区分大小写的精确短语匹配,那么它们可能是比标准索引更好的选择,因为它们的性能会更好。例如,在具有索引 { "t" : 1 }
的字段 t
上,完全匹配正则表达式
> db.test.find({ "t" : /#text/ })
执行全索引扫描。类似(但不等同)的文本查询
> db.test.find({ "$text" : { "$search" : "\"#text\"" } })
将使用文本索引来定位包含术语 "text"
的文档,然后扫描所有这些文档以查看它们是否包含完整的短语 "#text
"。
小心,因为文本索引不区分大小写。继续上面的例子:
> 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" }
Model.find({ $text : {$search: "#text"} })
returns 包含 "text" 的所有内容,而不仅仅是带有“#text”的那些文档。我试过在 # 前加一个 \,但没有用。如何阻止 mongodb 忽略我的特殊字符?谢谢。
Tomalak 对文本索引工作原理的描述是正确的,但实际上您可以对具有特殊字符的短语 exact phrase match 使用文本索引:
> 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" }
精确短语匹配用双引号括起短语表示,需要在 shell 中转义,如 "\"#text\""
.
文本索引比普通索引大,但如果您要进行大量不区分大小写的精确短语匹配,那么它们可能是比标准索引更好的选择,因为它们的性能会更好。例如,在具有索引 { "t" : 1 }
的字段 t
上,完全匹配正则表达式
> db.test.find({ "t" : /#text/ })
执行全索引扫描。类似(但不等同)的文本查询
> db.test.find({ "$text" : { "$search" : "\"#text\"" } })
将使用文本索引来定位包含术语 "text"
的文档,然后扫描所有这些文档以查看它们是否包含完整的短语 "#text
"。
小心,因为文本索引不区分大小写。继续上面的例子:
> 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" }