Mongomapper 对哈希键的查询
我有一个一天的模型,每一天都包含一个标签哈希。
class Day
include MongoMapper::Document
key :tags, Hash
...
end
标签哈希可能看起来像这样 {"a"=>4, "b"=>1, "c"=>1}
我想编写一个查询,可以找到带有标签键的所有日期等于“a”。
Day.where('tags.keys' => "a")
这是行不通的,因为键实际上并不是哈希中的键,我猜我不能只使用键方法。
我真的很想知道是否有办法查询哈希的键,否则我将不得不创建一个数组来存储键并查询它。
tags = {"a"=>4, "b"=>1, "c"=>1, "names" => ["a", "b", "c"]}
Day.where('tags.names' => "a") #This would work find, but is not what I want
I have a model for a Day and each day contains a tag hash.
class Day
include MongoMapper::Document
key :tags, Hash
...
end
The tags hash might look like this {"a"=>4, "b"=>1, "c"=>1}
I would like to write a query that can find all of the days with a tag key equal to 'a'.
Day.where('tags.keys' => "a")
This doesn't work, since keys is not actually a key in the hash and I'm guessing I can't just use the keys method.
I would really like to know if there is a way to query the keys of a hash, otherwise I will have to create an array to store the keys in and query that.
tags = {"a"=>4, "b"=>1, "c"=>1, "names" => ["a", "b", "c"]}
Day.where('tags.names' => "a") #This would work find, but is not what I want
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决办法。
Day.where('tags.a' => {'$exists' => true})
这将返回带有 'a' 键的所有日期。
事实上,我可以为 Day 编写一个方法,如下所示
然后很容易通过某个标签获取所有日期,如下所示:
I have found a solution.
Day.where('tags.a' => {'$exists' => true})
This will return all days with an 'a' key.
In fact I can write a method for Day like this
Then it would be easy to get all days by a certain tag like this: