Reputation: 5528
Is there a way to set an attribute in mongoid for case insensitive searches?
Lets say that somebody has a username: IAmGreat and I want to find the users data using their unique username without butchering it and changing it to iamgreat.
Thanks
Upvotes: 14
Views: 6893
Reputation: 4433
Actually you can search case insensitive. But you have to search with an regex! Here is an example how I'm using it at http://zeit.io
User.where(email: /\A#{Regexp.escape(email)}\z/i).first
With the /
you are starting and ending the regex. The i
after the regex means case insensitive. \A
Means the string has to start with the search string and \z
means the string has to end with the search string. This is important if you are looking for an exact match.
Upvotes: 52
Reputation: 1526
If your application doesn't need to store user-input as case-sensitive, just convert the input to uppercase or lowercase on the way in. Example,
username = params[:username].to_s.downcase
Otherwise, if performance is an issue for you (case-insensitive regex cannot take advantage for indexes) the right way to go about it is to store a backup field for username
field :username_downcase
And then do the query:
User.where(username_downcase: params[:username].to_s.downcase)
Upvotes: 0
Reputation: 2971
if you are using rails or mongoid you can try the ff:
@user = User.where({:username => /.*#{name}.*/i })
Upvotes: 3
Reputation: 2570
You can even try something like:
User.where(username: /#{username}/i).first
Upvotes: 7
Reputation: 33954
Why not just down a User.login.downcase
(or whatever your model/attribute combination is) when making the comparison? This will leave the capitalization in the DB as-is, but downcase the field just for comparison.
Upvotes: 1