1

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?

Zeck
  • 6,433
  • 21
  • 71
  • 111

3 Answers3

4

Try this

User.where(mobile: /.*#{params[:mobile]}.*/i)
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • Thank you for trying to help me but it's not work. I think the issue is `mobile` column is an `Integer`. – Zeck Sep 09 '14 at 09:01
1

SOLUTION:

users = User.where(:$where => "/^#{params[:mobile]}/.test(this.mobile)")
Zeck
  • 6,433
  • 21
  • 71
  • 111
0

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

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

dddd1919
  • 868
  • 5
  • 13
  • Hello, Thank you for trying to help me. I run your code but it's not work. Here is the command: `User.where(:mobile => /\d*8801\d*/).length`. It shows me 0. But in my db it's 32. – Zeck Sep 09 '14 at 08:41
  • Oh sorry, I ignore that `mobile` field is a `Integer`, `regexp` may only works with `String` filed. Why the `mobile` field use a integer type, if a mobile is `18892887374`, its so big for a integer. – dddd1919 Sep 09 '14 at 08:52
  • Because in my country's mobile number consists of 8 characters. Is there any way to do it? – Zeck Sep 09 '14 at 08:55
  • Use the ruby way `User.all.select {|u| u.mobile.to_s.include?(params[:mobile])}` – dddd1919 Sep 09 '14 at 08:57
  • Hmm, it will reduce my load time :( – Zeck Sep 09 '14 at 08:59
  • Yes, it may be a bit slow, will you consider change mobile field to string to use native function? – dddd1919 Sep 09 '14 at 09:09
  • Woohoo. I just make it work: `users = User.where(:$where => "/^#{params[:mobile]}/.test(this.mobile)")` – Zeck Sep 09 '14 at 09:16