2

So I have a document in a collection with on of the fields having a value "@@@" I indexed the collection and tried running the query:

db.getCollection('TestCollection').find({$text:{$search:"\"@@@\""}})

But it didn't show the result

How can I work around this?

Sample Document:

{
"_id" : ObjectId("5b90dc6d3de8562a6ef7c409"),
"field" : "value",
"field2" : "@@@"
}
Stennie
  • 63,885
  • 14
  • 149
  • 175
Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67

2 Answers2

2

Text search is designed to index strings based on language heuristics. Text indexing involves two general steps: tokenizing (converting a string into individual terms of interest) followed by stemming (converting each term into a root form for indexing based on language-specific rules).

During the tokenizing step certain characters (for example, punctuation symbols such as @) are classified as word separators (aka delimiters) rather than text input and used to separate the original string into terms. Language-specific stop words (common words such as "the", "is", or "on" in English) are also excluded from a text index.

Since your search phrase of @@@ consists entirely of delimiters, there is no corresponding entry in the text index.

If you want to match generic string patterns, you should use regular expressions rather than text search. For example: db.getCollection('TestCollection').find({field2:/@@@/}). However, please note the caveats on index usage for regular expressions.

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • @PrateekNarendra I'd suggest posting a new question with details on the actual outcome you are trying to achieve (rather than this text search approach which won't work if you want to match `@@@`). It would be helpful to include your specific version of MongoDB server and more context on the use case (such as additional sample documents and an explanation of the importance of `@@@`). Regular expressions definitely have usage caveats and there are likely more efficient ways to model your data to support your search use case. – Stennie Sep 07 '18 at 04:59
0

Your query has to many curly braces, remove them:

db.getCollection('so2').find({$text:{$search:"\"@@@\""}})

If you run it, Mongo tells you you're missing a text index. Add it like this:

db.so2.createIndex( { field2: "text" } )

The value you're using is pretty small. Try using longer values.

Clouren
  • 372
  • 1
  • 3
  • 10
  • 2
    This does not answer the question at all. While I agree there is an unnecessary set of curly braces in his $search, the issue is with the special characters that are not returned as a result. Mongo probably isn't going to tell him he's missing a text index, as he stated he already created one. I assume you were missing the index during your testing. The length of the query doesn't matter. – gbeaven Sep 06 '18 at 18:24
  • @Clouren I have created a text index on all fields in the collection – Prateek Narendra Sep 06 '18 at 21:04