简体   繁体   中英

Querying a hash in Mongoid

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM