Use LIKE/regex with variable in mongoid

后端 未结 5 1999
悲哀的现实
悲哀的现实 2021-02-01 18:40

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

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

H

5条回答
  •  死守一世寂寞
    2021-02-01 18:54

    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/" 
    

提交回复
热议问题