0

Env:

MongoDB (4.0.6) 

At the beginning I was used regex search like this:

keyword = new RegExp(keyword, 'img');
query.$or = [
  { campaignTitle: keyword }
];

but main problem, "keyword" it just inputs value and if the user used specific symbols it`s broked my regex... To solve this problem I added text index to the collection and start to use text search like this:

//Text Index creation:
db.collection('campaignmodel').createIndex({ campaignTitle: 'text' }, { background: true });

query.$or = [
    { $text: { $search: keyword } }
];

It's working, but not comfortable for the user because search can`t find campaignTitle by part of word.

I already investigated these docs:

https://docs.mongodb.com/manual/text-search/ (important quote- "$text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.")

MongoDB Full and Partial Text Search (maybe it is already not actual information)

for campaignTitle - "testCompnew Copy 3/14/2019"

now I can find it use these inputs:

"Copy", "copy", "2019", "3/", "testCompnew" 

but can`t use these inputs:

"new", "test", "Comp"

Is it possible to do a search by text index in MongoDB with only a part of the word?

user2342558
  • 5,567
  • 5
  • 33
  • 54

1 Answers1

0
Try it using $regex -- refer below link,

Click here for more!

---------------To use $regex, use one of the following syntaxes:-------------
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

In MongoDB, you can also use regular expression objects (i.e. /pattern/) to specify regular expressions:
{ <field>: /pattern/<options> }

***As an example: { <text>: /new/ }
Tharindu Lakshan
  • 3,995
  • 6
  • 24
  • 44