在 mongoid 中搜索单词时不区分大小写
有没有办法在 mongoid 中设置属性以进行不区分大小写的搜索?
假设某人有一个用户名:IAmGreat,我想使用其唯一的用户名查找用户数据,而不会将其删除并将其更改为 iamgreat。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其实你可以搜索不区分大小写。但你必须使用正则表达式进行搜索!
这是我如何在 http://zeit.io 上使用它的示例,
其中
/ 您正在开始和结束正则表达式。正则表达式后面的
i
表示不区分大小写。\A
表示字符串必须以搜索字符串开头,\z
表示字符串必须以搜索字符串结束。如果您正在寻找完全匹配的内容,这一点很重要。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
With the
/
you are starting and ending the regex. Thei
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.你甚至可以尝试这样的事情:
You can even try something like:
如果您使用的是 Rails 或 mongoid,您可以尝试 ff:
@user = User.where({:username => /.*#{name}.*/i })
if you are using rails or mongoid you can try the ff:
@user = User.where({:username => /.*#{name}.*/i })
为什么在进行比较时不直接使用
User.login.downcase
(或任何模型/属性组合)?这将使数据库中的大写保持不变,但将字段小写以供比较。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.如果您的应用程序不需要将用户输入存储为区分大小写,只需在输入时将输入转换为大写或小写即可。例如,
否则,如果性能对您来说是一个问题(不区分大小写的正则表达式无法利用索引)正确的方法是存储用户名的备份字段
然后执行查询:
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,
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
And then do the query: