Use LIKE/regex with variable in mongoid Use LIKE/regex with variable in mongoid mongodb mongodb

Use LIKE/regex with variable in mongoid


searchterm = (params[:searchlogparams][:searchterm])@tweets = Tweet.any_of({ :text => Regexp.new ("/.*"+searchterm+".*/") })

or

searchterm = (params[:searchlogparams][:searchterm])@tweets = Tweet.any_of({ :text => /.*#{searchterm}.*/ })


There is nothing wrong with the mongodb regex query. The problem is passing variable to ruby regex string. You cannot mix string with regex like normal strings

Instead

 "/.*"+searchterm+".*/"

try this

  >>searchterm = "test"  >>"/#{searchterm}/"  >> "/test/" 


@tweets = Tweet.any_of({ :text => Regexp.new (".*"+searchterm+".*") })

is ok and have result