数组中元素的 Mongoid 正则表达式
我有两个模型,一个用户和一个嵌入式模型消息,
class User
include Mongoid::Document
embeds_many :messages
end
class Message
include Mongoid::Document
field :keywords, :type => Array
end
我正在尝试执行类似的操作:
u = User.last
u.messages.where(:keywords => /sometext/).first
但这不会返回任何内容,如果字段不是 Array
类型并且是 <代码>字符串。我怎样才能用 Mongoid 做这样的事情?
我还应该提到这个 Mongo 查询工作正常:
db.users.find({"messages.keywords" : /index/ })
I have two models, a User and an embedded model Message
class User
include Mongoid::Document
embeds_many :messages
end
class Message
include Mongoid::Document
field :keywords, :type => Array
end
I am trying to do something like:
u = User.last
u.messages.where(:keywords => /sometext/).first
But this returns nothing, the regex seems to work fine if the field is not of type Array
and is a String
. How can I do something like this with Mongoid?
I should also mention this Mongo query works fine:
db.users.find({"messages.keywords" : /index/ })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你正在处理一个数组,你可以使用“in”。
如果我没记错的话应该可以。
Alex
现在您拥有了消息并且可以执行任何操作,但是您无法获取所有用户的消息集合,这样就不行了。
If you are dealing with an array, you use "in".
should work if I am not mistaken.
Alex
Now you have your messages and can do whatever, but you can't get a collections of messages for all users it does not work that way.
您的直接 Mongo 查询正在查找所有嵌入了具有指定匹配子字符串的消息的用户文档。看起来您的 Mongoid 查询的目的是在已返回的用户文档上查找匹配的消息。我不确定您正在寻找哪种行为,但如果您想在 Mongoid 中执行相同的 Mongo 直接查询,它看起来像这样:
Your direct Mongo query is finding all user documents that have embedded messages with the specified matching substring. It looks like the intention of your Mongoid query is to find a matching message on an already returned user document. I'm not sure which behavior you're looking for, but if you want to perform the same Mongo-direct query in Mongoid, it would look something like this: