Reputation: 1445
I have created a product document that looks as follows:
#<Product _id: 539ac4285468691170000000, created_at: 2014-06-13 09:28:08 UTC, updated_at: 2014-06-13 10:28:57 UTC, properties: {"first"=>{"element_1"=>"test", "element_2"=>"bigtest"}, "second"=>"layer_one"}>
Now I have read a lot about querying using where()
. Yet I have not found any information whether it is possible and if yes how to extract individual elements of a hash.
How can I query something like this:
ruby 2.0.0p451 > w = Product.last
ruby 2.0.0p451 > w.properties.first
ruby 2.0.0p451 > w.properties.first.element_2
ruby 2.0.0p451 > w.properties.first.push("element_3"=>"grandetest")
Can you please point to a reference where I could see more Mongoid querying examples and in particular to such ones that extract individual components of a hash. Thanks so much.
Upvotes: 0
Views: 72
Reputation: 5535
This is how you need to access to hash values:
> w.properties['first']
=> {"element_1"=>"test", "element_2"=>"bigtest"}
> w.properties['first']['element_2']
=> "bigtest"
> w.properties['first']['element_3'] = "grandetest"
=> {"element_1"=>"test", "element_2"=>"bigtest", "element_3"=>"grandetest"}
You can use 'where' to search a Product by a value of 'element_2' for example:
> Product.where("properties.first.element_2" => "bigtest").count
=> 1
I hope you will be helpful.
Upvotes: 0