23

I'm trying to find all documents whose text contains the word test. The below works fine:

@tweets = Tweet.any_of({ :text => /.*test.*/ })

However, I want to be able to search for a user supplied string. I thought the below would work but it doesn't:

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

I've tried everything I could think of, anyone know what I could do to make this work.

Thanks in advance.

Hinchy
  • 683
  • 2
  • 7
  • 19

5 Answers5

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

or

searchterm = (params[:searchlogparams][:searchterm])
@tweets = Tweet.any_of({ :text => /.*#{searchterm}.*/ })
Timmy
  • 100
  • 9
Nat
  • 3,587
  • 20
  • 22
  • What I need to do if i want to search like there is location Mumbai and I am passing the location like Mumbai, Maharashtra , India. But it is not searching.. here is my query Event.any_of(location: /.*mumbai maharashtra.*/is).entries. Its not working but if I pass a mumbai then its working. Please suggest. – Mohd Anas Nov 26 '14 at 05:36
15

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/" 
RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • 4
    Thanks a bunch, Ramesh. I had to remove the " at start and end and then your example worked perfectly. Brilliant! – Hinchy Dec 15 '11 at 16:49
1
@tweets = Tweet.any_of({ :text => Regexp.new (".*"+searchterm+".*") })

is ok and have result

kleopatra
  • 51,061
  • 28
  • 99
  • 211
sitoto
  • 11
  • 1
0

This worked for me by doing:

Model.find(:all, :conditions => {:field => /regex/i})
methodofaction
  • 70,885
  • 21
  • 151
  • 164
0
@tweets = Tweet.any_of({ :text => Regexp.new ("/.*"+searchterm+".*/") })  

is work, but no result

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

is ok and have result

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

is work, no result

My mongoid version is 3.1.3 and ruby version is 1.9.3

shooter
  • 9
  • 1