简体   繁体   English

在Mongoid中查询哈希

[英]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() . 现在,我已经阅读了很多有关使用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. 您能否指向参考文献,在那里我可以看到更多的Mongoid查询示例,尤其是那些提取哈希的各个组成部分的示例。 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: 您可以使用“ where”按“​​ element_2”值搜索产品,例如:

> Product.where("properties.first.element_2" => "bigtest").count
=> 1

I hope you will be helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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