Mongoid 4: like query on integer column

2019-07-21 09:13发布

I need a mongoid search like query with INTEGER COLUMN. For example:

SELECT * FROM users WHERE mobile LIKE '%9980%';

Here is the my model:

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  ##
  # Columns
  field :name,                      type: String
  field :mobile,                    type: Integer
end

I already tried following examples. But no luck :(

User.where(:$where => "/^#{params[:mobile]}/")
User.any_of({mobile: /.*#{params[:mobile]}.*/i})
User.where(mobile: /8801/))

How to write it with mongoid?

3条回答
甜甜的少女心
2楼-- · 2019-07-21 09:45

SOLUTION:

users = User.where(:$where => "/^#{params[:mobile]}/.test(this.mobile)")
查看更多
可以哭但决不认输i
3楼-- · 2019-07-21 09:52

Try this

User.where(mobile: /.*#{params[:mobile]}.*/i)
查看更多
聊天终结者
4楼-- · 2019-07-21 09:56

User.where(:mobile => /\d*{params[:mobile]}\d*/)

Like function in Mongoid is just instead the arguement of where to regexp

查看更多
登录 后发表回答