Getting a hash with a symbol as keys for mongo in rails

The Mongo ruby ​​driver seems to put your results in a hash with strings as keys. Is there a way to say to convert keys to characters instead?

+4
source share
2 answers

According to the FAQ , even though Mongo has a character type, and you can store characters in values, the BSON format indicates that keys must be strings.

+6
source

If you have a Hash that is associated with strings, and you want to use Symbol as keys to access its values, you can use HashWithIndifferentAccess . If you are not using Rails, you can get this class using the ActiveSupport gem.

 my_hash = { 'name' => 'Joe', 'email' => ' joe@schmoe.com ' } my_hash = HashWithIndifferentAccess.new my_hash puts my_hash[:name] # "Joe" 
+4
source

Source: https://habr.com/ru/post/1341376/


All Articles