在 mongoid 中搜索单词时不区分大小写

发布于 2024-12-05 03:37:49 字数 121 浏览 2 评论 0原文

有没有办法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

木格 2024-12-12 03:37:50

其实你可以搜索不区分大小写。但你必须使用正则表达式进行搜索!
这是我如何在 http://zeit.io 上使用它的示例,

User.where(email: /\A#{Regexp.escape(email)}\z/i).first

其中 / 您正在开始和结束正则表达式。正则表达式后面的 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

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.

默嘫て 2024-12-12 03:37:50

你甚至可以尝试这样的事情:

User.where(username: /#{username}/i).first

You can even try something like:

User.where(username: /#{username}/i).first
相权↑美人 2024-12-12 03:37:50

如果您使用的是 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 })

待天淡蓝洁白时 2024-12-12 03:37:50

为什么在进行比较时不直接使用 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.

我的影子我的梦 2024-12-12 03:37:50

如果您的应用程序不需要将用户输入存储为区分大小写,只需在输入时将输入转换为大写或小写即可。例如,

username = params[:username].to_s.downcase

否则,如果性能对您来说是一个问题(不区分大小写的正则表达式无法利用索引)正确的方法是存储用户名的备份字段

field :username_downcase

然后执行查询:

User.where(username_downcase: params[:username].to_s.downcase)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文