Reputation: 2565
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
Upvotes: 3
Views: 1227
Reputation: 2565
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
def self.find_all_by_tag(tag)
Day.where("tags.#{tag}" => {'$exists' => true}).all
end
Then it would be easy to get all days by a certain tag like this:
Day.find_all_by_tag("a")
Upvotes: 5