Model.find({ $text : {$search: "#text"} })
返回包含「文本」的所有內容,不僅包含帶「#text」的文檔。我已經嘗試在#之前放置\,無濟於事。我該如何阻止mongodb忽視我的特殊字符?謝謝。停止mongodb忽視特殊字符?
Model.find({ $text : {$search: "#text"} })
返回包含「文本」的所有內容,不僅包含帶「#text」的文檔。我已經嘗試在#之前放置\,無濟於事。我該如何阻止mongodb忽視我的特殊字符?謝謝。停止mongodb忽視特殊字符?
的文本索引如何工作託默勒格的描述是正確的,但實際上你可以在一個短語使用的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" }
精確短語匹配由圍繞一語中的指示雙引號,需要在外殼中轉義,如"\"#text\""
。
文本索引大於正常索引,但如果您正在執行大量不區分大小寫的精確詞組匹配,那麼它們可能比標準索引更好,因爲它們的性能會更好。例如,在一個場t
與索引{ "t" : 1 }
,精確匹配正則表達式
> 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" }
的
可能重複[如何查詢的MongoDB用「像」?](http://stackoverflow.com/questions/3305561/how- to-query-mongodb-like-like) – Tomalak 2015-02-07 08:50:29
'$ text'是一個全文搜索。它不適用於確切的子字符串匹配,它搜索單詞形式和短語,就像搜索引擎一樣。使用正則表達式來完成匹配。 – Tomalak 2015-02-07 08:54:28
如果我搜索「xtext」,那麼帶有「文本」的文檔不會顯示出來,爲什麼它與「#text」不同? – user36322 2015-02-07 10:50:37