Stop mongodb from ignoring special characters?

2020-04-20 02:36发布

Model.find({ $text : {$search: "#text"} })

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.

标签: mongodb
1条回答
够拽才男人
2楼-- · 2020-04-20 03:00

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" }
查看更多
登录 后发表回答