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.
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.
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:
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 regexperforms a full index scan. The analogous (but not equivalent) text query
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: