Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a hash from a BSON document in Ruby?

I save a hash into MongoDB using the Mongo gem. I then get a BSON::Document back when I query the database in Ruby.

How do I convert the BSON::Document back to the original hash?

doc = { name: 'Steve', hobbies: [ 'hiking', 'tennis', 'fly fishing' ] }

result = collection.insert_one(doc)

steve = collection.find( { name: 'Steve' } ).first

returns:

{"_id"=>BSON::ObjectId('5baf68cd65992f3734f396ab'), "name"=>"Steve", "hobbies"=>["hiking", "tennis", "fly fishing"]}

like image 259
nilanjan Avatar asked Mar 23 '26 11:03

nilanjan


1 Answers

As per the details mentioned in the post it seems like you want to convert BSON db object to json(Hash) object.

BSON contains JSON module which provides the below mentioned method to convert object to json

to_json

https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/JSON

Not sure of the below mentioned method, as I have only used it in ActiveRecord object, try if it works

result.as_json(only: ["name_of_the_column_you_want"])
like image 119
Rohan Avatar answered Mar 25 '26 01:03

Rohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!